package com.junzhiit.nengji.shop.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bainaeco.framework.util.DateUtil;
import com.bainaeco.framework.util.serializer.Format;
import com.junzhiit.nengji.bo.CartBO;
import com.junzhiit.nengji.bo.GoodsBO;
import com.junzhiit.nengji.bo.GoodsDetailBO;
import com.junzhiit.nengji.bo.MemberCardUseBO;
import com.junzhiit.nengji.bo.OrdersBO;
import com.junzhiit.nengji.bo.OrdersGoodsBO;
import com.junzhiit.nengji.bo.ShopDetailBO;
import com.junzhiit.nengji.bo.UserBO;
import com.junzhiit.nengji.bo.UserCouponsInfoBO;
import com.junzhiit.nengji.bo.WechatConfigBO;
import com.junzhiit.nengji.dao.AddressDAO;
import com.junzhiit.nengji.dao.BalanceHistoryDAO;
import com.junzhiit.nengji.dao.BookingDAO;
import com.junzhiit.nengji.dao.CartDAO;
import com.junzhiit.nengji.dao.ChainDAO;
import com.junzhiit.nengji.dao.DetailIntegralDAO;
import com.junzhiit.nengji.dao.GoodsDAO;
import com.junzhiit.nengji.dao.GoodsDataHistoryDAO;
import com.junzhiit.nengji.dao.IndustryDAO;
import com.junzhiit.nengji.dao.MemberCardDAO;
import com.junzhiit.nengji.dao.MemberCardHistoryDAO;
import com.junzhiit.nengji.dao.MemberCardUseDAO;
import com.junzhiit.nengji.dao.OrdersDAO;
import com.junzhiit.nengji.dao.OrdersDataHistoryDAO;
import com.junzhiit.nengji.dao.OrdersGoodsDAO;
import com.junzhiit.nengji.dao.PayHistoryDAO;
import com.junzhiit.nengji.dao.ShopClientDAO;
import com.junzhiit.nengji.dao.ShopDAO;
import com.junzhiit.nengji.dao.SkuContentDAO;
import com.junzhiit.nengji.dao.SystemConfigDAO;
import com.junzhiit.nengji.dao.UserConfigDAO;
import com.junzhiit.nengji.dao.UserCouponsDAO;
import com.junzhiit.nengji.dao.UserDAO;
import com.junzhiit.nengji.dao.UserGoodsDAO;
import com.junzhiit.nengji.dao.UserVipDAO;
import com.junzhiit.nengji.dao.VipHistoryDAO;
import com.junzhiit.nengji.dao.WechatConfigDAO;
import com.junzhiit.nengji.dao.cache.UserCacheDAO;
import com.junzhiit.nengji.dao.cache.WechatConfigCacheDAO;
import com.junzhiit.nengji.dao.util.DIYKey;
import com.junzhiit.nengji.model.Address;
import com.junzhiit.nengji.model.BalanceHistory;
import com.junzhiit.nengji.model.Booking;
import com.junzhiit.nengji.model.Chain;
import com.junzhiit.nengji.model.DetailIntegral;
import com.junzhiit.nengji.model.Goods;
import com.junzhiit.nengji.model.GoodsDataHistory;
import com.junzhiit.nengji.model.Industry;
import com.junzhiit.nengji.model.MemberCard;
import com.junzhiit.nengji.model.MemberCardHistory;
import com.junzhiit.nengji.model.MemberCardUse;
import com.junzhiit.nengji.model.Orders;
import com.junzhiit.nengji.model.OrdersDataHistory;
import com.junzhiit.nengji.model.OrdersGoods;
import com.junzhiit.nengji.model.PayHistory;
import com.junzhiit.nengji.model.RebateInfo;
import com.junzhiit.nengji.model.Shop;
import com.junzhiit.nengji.model.ShopClient;
import com.junzhiit.nengji.model.SkuContent;
import com.junzhiit.nengji.model.SystemConfig;
import com.junzhiit.nengji.model.User;
import com.junzhiit.nengji.model.UserConfig;
import com.junzhiit.nengji.model.UserCoupons;
import com.junzhiit.nengji.model.UserGoods;
import com.junzhiit.nengji.model.UserVip;
import com.junzhiit.nengji.model.VipHistory;
import com.junzhiit.nengji.model.WechatConfig;
import com.junzhiit.nengji.model.enums.BalanceHistoryOperation;
import com.junzhiit.nengji.model.enums.BalanceHistoryStatus;
import com.junzhiit.nengji.model.enums.BookingStatus;
import com.junzhiit.nengji.model.enums.ConfirmType;
import com.junzhiit.nengji.model.enums.CouponFullSubtraction;
import com.junzhiit.nengji.model.enums.CouponsPlatform;
import com.junzhiit.nengji.model.enums.CouponsType;
import com.junzhiit.nengji.model.enums.DetailStatus;
import com.junzhiit.nengji.model.enums.DetailType;
import com.junzhiit.nengji.model.enums.Is;
import com.junzhiit.nengji.model.enums.IsChainStatus;
import com.junzhiit.nengji.model.enums.IsUse;
import com.junzhiit.nengji.model.enums.MemberCardUseType;
import com.junzhiit.nengji.model.enums.MemberCardValidTime;
import com.junzhiit.nengji.model.enums.OrderStatus;
import com.junzhiit.nengji.model.enums.OrderType;
import com.junzhiit.nengji.model.enums.OrdersDataHistoryStatus;
import com.junzhiit.nengji.model.enums.PayHistoryType;
import com.junzhiit.nengji.model.enums.PayWay;
import com.junzhiit.nengji.model.enums.PostageType;
import com.junzhiit.nengji.model.enums.ShopClientStatus;
import com.junzhiit.nengji.model.enums.TransactionType;
import com.junzhiit.nengji.model.enums.UserGoodsType;
import com.junzhiit.nengji.model.enums.UserVipType;
import com.junzhiit.nengji.shop.service.CommissionHistoryService;
import com.junzhiit.nengji.shop.service.CouponsService;
import com.junzhiit.nengji.shop.service.MemberCardService;
import com.junzhiit.nengji.shop.service.OrdersGoodsService;
import com.junzhiit.nengji.shop.service.OrdersService;
import com.junzhiit.nengji.shop.service.PrintingService;
import com.junzhiit.nengji.shop.service.RebateService;
import com.junzhiit.nengji.shop.service.TransactionService;
import com.junzhiit.nengji.shop.service.UserCouponsService;
import com.junzhiit.nengji.shop.web.exception.BalanceInsufficientException;
import com.junzhiit.nengji.shop.web.exception.ChainShopException;
import com.junzhiit.nengji.shop.web.exception.GoodsNotFoundException;
import com.junzhiit.nengji.shop.web.exception.LogisticsNumberErrorException;
import com.junzhiit.nengji.shop.web.exception.NotFoundException;
import com.junzhiit.nengji.shop.web.exception.OrderNotFoundException;
import com.junzhiit.nengji.shop.web.exception.OrdersGoodsNotFoundException;
import com.junzhiit.nengji.shop.web.exception.OrdersNotFoundException;
import com.junzhiit.nengji.shop.web.exception.SkuContentNotFoundException;
import com.junzhiit.nengji.shop.web.exception.UserNotFoundException;
import com.junzhiit.nengji.shop.web.exception.UserVipNotFoundException;
import com.junzhiit.nengji.shop.web.exception.WechatConfigAddException;
import com.junzhiit.nengji.shop.web.util.APICodeStatus;
import com.junzhiit.nengji.shop.web.util.Constants;
import com.junzhiit.nengji.shop.web.util.FileUtil;
import com.junzhiit.nengji.shop.web.util.OrderNumberUtils;
import com.junzhiit.nengji.shop.web.util.RequestUtil;
import com.junzhiit.nengji.shop.web.util.aliyun.AliyunOSSClientUtil;
import com.junzhiit.nengji.shop.web.util.aliyun.LogisticsUtil;
import com.junzhiit.nengji.shop.web.util.aliyun.bean.LogisticsResultDate;
import com.junzhiit.nengji.shop.web.util.tools.NumberUtils;
import com.junzhiit.nengji.shop.web.util.wechat.MessageUtil;
import com.junzhiit.nengji.shop.web.util.wechat.TemplateMessageUtil;
import com.junzhiit.nengji.shop.web.util.wechat.WeChatUtils;
import com.junzhiit.nengji.shop.web.util.wechat.bean.OrderInfo;
import com.junzhiit.nengji.shop.web.util.wechat.bean.PayParam;
import com.junzhiit.nengji.shop.web.util.wechat.bean.TemplateMessageParam;
import com.junzhiit.nengji.shop.web.vo.AddressVO;
import com.junzhiit.nengji.shop.web.vo.CouponsDetailsVO;
import com.junzhiit.nengji.shop.web.vo.CreateOrderVO;
import com.junzhiit.nengji.shop.web.vo.ListVO;
import com.junzhiit.nengji.shop.web.vo.MemberCardUseVO;
import com.junzhiit.nengji.shop.web.vo.OrderInfoGoodsVO;
import com.junzhiit.nengji.shop.web.vo.OrderInfoVO;
import com.junzhiit.nengji.shop.web.vo.OrdersGoodsVO;
import com.junzhiit.nengji.shop.web.vo.OrdersPaySuccessVO;
import com.junzhiit.nengji.shop.web.vo.OrdersShopVO;
import com.junzhiit.nengji.shop.web.vo.OrdersVO;
import com.junzhiit.nengji.shop.web.vo.RebateVO;
import com.junzhiit.nengji.shop.web.vo.ResultVO;
import com.junzhiit.nengji.shop.web.vo.TransactionAddVO;
import com.junzhiit.nengji.shop.web.vo.UserFormIdVO;

@Service
public class OrdersServiceImpl extends BaseServiceImpl implements OrdersService {

	@Autowired
	private OrdersDAO ordersDAO;

	@Autowired
	private OrdersGoodsDAO ordersGoodsDAO;

	@Autowired
	private OrdersGoodsService ordersGoodsService;

	@Autowired
	private GoodsDAO goodsDAO;

	@Autowired
	private AddressDAO addressDAO;

	@Autowired
	private UserDAO userDAO;

	@Autowired
	private CartDAO cartDAO;

	@Autowired
	private UserGoodsDAO userGoodsDAO;

	@Autowired
	private PayHistoryDAO payHistoryDAO;

	@Autowired
	private SkuContentDAO skuContentDAO;

	@Autowired
	private TransactionService transactionService;

	@Autowired
	private SystemConfigDAO systemConfigDAO;

	@Autowired
	private RebateService rebateService;

	@Autowired
	private CommissionHistoryService commissionHistoryService;

	@Autowired
	private ShopDAO shopDAO;

	@Autowired
	private UserVipDAO userVipDAO;

	@Autowired
	private VipHistoryDAO vipHistoryDAO;

	@Autowired
	private UserConfigDAO userConfigDAO;

	@Autowired
	private UserCouponsDAO userCouponsDAO;

	@Autowired
	private OrdersDataHistoryDAO ordersDataHistoryDAO;

	@Autowired
	private GoodsDataHistoryDAO goodsDataHistoryDAO;

	@Autowired
	private IndustryDAO industryDAO;

	@Autowired
	private UserCouponsService userCouponsService;

	@Autowired
	private CouponsService couponsService;

	@Autowired
	private UserCacheDAO userCacheDAO;

	@Autowired
	private WechatConfigCacheDAO wechatConfigCacheDAO;

	@Autowired
	private WechatConfigDAO wechatConfigDAO;

	@Autowired
	private ChainDAO chainDAO;

	@Autowired
	private BalanceHistoryDAO balanceHistoryDAO;

	@Autowired
	private ShopClientDAO shopClientDAO;

	@Autowired
	private MemberCardUseDAO memberCardUseDAO;

	@Autowired
	private MemberCardDAO memberCardDAO;

	@Autowired
	private MemberCardService memberCardService;

	@Autowired
	private MemberCardHistoryDAO memberCardHistoryDAO;
	
	@Autowired
	private BookingDAO bookingDAO;

	@Autowired
	private PrintingService printingService;
	
	@Autowired
	private DetailIntegralDAO detailIntegralDAO;

	private final String WECHAT_BODY_KEY = "乐鸽订单";

	// private final String WECHAT_BODY_KEY = "wechat.body";

	@Value("${images.qrcode.order.path}")
	private String qrcodePath;
	
	@Value("${images.data.qrcode.order.path}")
	private String dataQrcodePath;
	
	//阿里云API的bucket名称
	@Value("${oss.backet.name}")
	private String backetName;
	
	@Override
	public ResultVO findAllOrders(Integer pageNumber, Integer maxPageRow, Integer status, Integer type, String userId,
			String shopId) {
		ResultVO result = new ResultVO();
		List<OrdersBO> orderList = ordersDAO.orders(pageNumber, maxPageRow, status, type, userId, shopId);
		if (orderList.size() == 0) {
			result.setStatus(APICodeStatus.GOODS_LIST_IS_EMPTY);
			result.setMessage("goods list is empty.");
			return result;
		}
		List<OrdersVO> list = new ArrayList<OrdersVO>();
		Boolean isEmpty = true;
		for (OrdersBO ordersBO : orderList) {
			OrdersVO ordersVO = new OrdersVO();
			ordersVO.setId(ordersBO.getId());
			ordersVO.setCreatedTime(ordersBO.getCreatedTime());
			ordersVO.setStatus(ordersBO.getStatus());
			ordersVO.setPostage(ordersBO.getPostage());
			ordersVO.setPayWay(ordersBO.getPayWay());
			ordersVO.setShopName(ordersBO.getShopName());
			ordersVO.setPayMoney(ordersBO.getPayMoney());
			ordersVO.setShopId(ordersBO.getShopId());
			ordersVO.setOrderNumber(ordersBO.getOrderNumber());
			ordersVO.setShopHeadImgUrl(ordersBO.getShopHeadImgUrl());
			ordersVO.setShopOrderNumber(ordersBO.getShopOrderNumber());
			ordersVO.setLogisticsNumber(ordersBO.getLogisticsNumber());
			ordersVO.setType(ordersBO.getType());
			List<OrdersGoodsBO> orderGoodsBOList = ordersGoodsDAO.getOrderGoods(ordersBO.getId());
			for (OrdersGoodsBO orderGoodsBO : orderGoodsBOList) {
				OrdersGoodsVO ordersGoodsVO = new OrdersGoodsVO();
				ordersGoodsVO.setId(orderGoodsBO.getId());
				ordersGoodsVO.setCoverImage(orderGoodsBO.getCoverImage());
				ordersGoodsVO.setType(orderGoodsBO.getType());
				ordersGoodsVO.setCode(orderGoodsBO.getCode());
				ordersGoodsVO.setBarcode(orderGoodsBO.getBarcode());
				ordersGoodsVO.setName(orderGoodsBO.getName());
				ordersGoodsVO.setNumber(orderGoodsBO.getNumber());
				ordersGoodsVO.setIsOpenSku(orderGoodsBO.getIsOpenSku());
				ordersGoodsVO.setStandard(orderGoodsBO.getStandard());
				ordersGoodsVO.setPrice(orderGoodsBO.getPrice());
				ordersGoodsVO.setReferencePrice(orderGoodsBO.getReferencePrice());
				ordersVO.addGoods(ordersGoodsVO);
				isEmpty = false;
			}

			list.add(ordersVO);
		}
		if (isEmpty) {
			result.setStatus(APICodeStatus.GOODS_LIST_IS_EMPTY);
			result.setMessage("Goods empty.");
			return result;
		}
		int totalCount = ordersDAO.getGoodsTotalCount(status, userId, type);
		ListVO listVO = new ListVO();
		listVO.setIndex(pageNumber);
		listVO.setCount(totalCount);
		listVO.setList(list);

		result.setData(listVO);
		result.setMessage("order success.");
		return result;
	}

	@Override
	public ResultVO changeStatus(String id, Integer status) {
		ResultVO result = new ResultVO();
		try {
			Orders orders = new Orders();
			orders.setId(id);
			orders.setStatus(status);
			if (status == OrderStatus.COMPLETE.toIntValue()) {
				orders.setCompleteTime(new Date());
			}
			// 还原优惠劵状态
			if (status == OrderStatus.CANCEL.toIntValue() || status == OrderStatus.FAILIN.toIntValue()
					|| status == OrderStatus.FAIL.toIntValue()) {
				userCouponsDAO.updateUserCoupons(id);
			}
			if (status == OrderStatus.PAID.toIntValue()) {
				orders.setPayTime(new Date());
			}
			result.setData(ordersDAO.update(orders));
		} catch (Exception e) {
			result.setStatus(APICodeStatus.ORDER_UPDATE_STATUS_IS_FAIL);
			result.setMessage("order update status fail.");
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public ResultVO findOrderInfo(String userId, String goods) {
		ResultVO result = new ResultVO();
		OrderInfoVO orderInfoVO = new OrderInfoVO();

		List<OrderInfoGoodsVO> goodsList = new ArrayList<OrderInfoGoodsVO>();

		// 商品
		String[] goodsArray = goods.split(";");// number_goodsId_shopId_skuContentId
		Boolean isGoodsEmpty = true;
		Map<String, OrdersShopVO> shopIds = new HashMap<String, OrdersShopVO>();
		String shopId = "";
		// 餐盒费
		Double foodBoxCharge = new Double(0);
		try {
			for (int i = 0; i < goodsArray.length; i++) {
				String[] goodsInfo = goodsArray[i].split("_");

				Integer number = Integer.valueOf(goodsInfo[0]);
				GoodsBO goodsBO = null;
				if (goodsInfo.length == 4) {
					goodsBO = goodsDAO.getGoodsByBarcode(userId, goodsInfo[2], goodsInfo[1], goodsInfo[3]);// sku
				} else {
					goodsBO = goodsDAO.getGoodsInfo(userId, goodsInfo[2], goodsInfo[1]);// not
																						// sku
				}
				if ("" == shopId) {
					shopId = goodsInfo[2];
				}
				// shop info
				OrdersShopVO shopInfo = new OrdersShopVO();
				shopInfo.setShopId(goodsBO.getShopId());
				shopInfo.setShopName(goodsBO.getShopName());
				shopInfo.setShopLogo(goodsBO.getShopHeadImgUrl());
				shopInfo.setType(goodsBO.getShopType());
				shopInfo.setPostageType(goodsBO.getPostageType());
				if (goodsBO.getPostageType() == PostageType.UNIFY.toIntValue()) {
					shopInfo.setPostagePrice(goodsBO.getPostagePrice());
				} else if (goodsBO.getPostageType() == PostageType.TEMPLATE.toIntValue()) {
					shopInfo.setPostageTemplateId(goodsBO.getPostageTemplateId());
				}
				shopIds.put(goodsInfo[2], shopInfo);

				// goods info
				if (goodsBO != null && StringUtils.isNotBlank(goodsBO.getId())) {
					OrderInfoGoodsVO orderInfoGoodsVO = new OrderInfoGoodsVO();
					BeanUtils.copyProperties(goodsBO, orderInfoGoodsVO);
					orderInfoGoodsVO.setNumber(number);
					foodBoxCharge += goodsBO.getFoodBoxCharge();
					goodsList.add(orderInfoGoodsVO);
					isGoodsEmpty = false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			isGoodsEmpty = true;
		}
		if (isGoodsEmpty) {
			result.setStatus(APICodeStatus.GOODS_NOT_FOUND);
			result.setMessage("Goods not found.");
			return result;
		}

		Double shopPostageMoney = 0.00;// 店铺运费
		Double shopGoodMoney = 0.00;
		Double sumPostageMoney = 0.00;// 订单总运费
		Double sumPayMoney = 0.0;// 实际支付金额
		Integer sumNumber = 0;
		List<Double> postageArray = new ArrayList<Double>();
		List<OrdersShopVO> shopList = new ArrayList<OrdersShopVO>();
		for (OrdersShopVO ordersShopVO : shopIds.values()) {
			for (OrderInfoGoodsVO orderInfoGoodsVO : goodsList) {
				if (orderInfoGoodsVO.getShopId().equals(ordersShopVO.getShopId())) {
					ordersShopVO.addGoods(orderInfoGoodsVO);
					// 商品总价
					shopGoodMoney += orderInfoGoodsVO.getPrice() * orderInfoGoodsVO.getNumber();
					sumNumber += orderInfoGoodsVO.getNumber();
					if (orderInfoGoodsVO.getPostagePrice() == null) {
						orderInfoGoodsVO.setPostagePrice(0.0);
					}
					if (orderInfoGoodsVO.getPostageType() == PostageType.POSTAGE.toIntValue()) {
						postageArray.add(0.0);
					} else {
						postageArray.add(orderInfoGoodsVO.getPostagePrice());
					}
				}
			}

			shopPostageMoney = Collections.max(postageArray);
			ordersShopVO.setPostage(shopPostageMoney);
			ordersShopVO.setRealMoney(shopGoodMoney);
			ordersShopVO.setPayMoney(Format.decimal(shopGoodMoney + shopPostageMoney));
			ordersShopVO.setSumNumber(sumNumber);

			shopList.add(ordersShopVO);
			sumPostageMoney += shopPostageMoney;
			sumPayMoney += shopGoodMoney;

			shopPostageMoney = 0.00;
			shopGoodMoney = 0.00;
			sumNumber = 0;
		}
		sumPayMoney += sumPostageMoney;
		orderInfoVO.setPostage(Format.decimal(sumPostageMoney));// 总运费
		orderInfoVO.setSumMoney(Format.decimal(sumPayMoney));// 支付金额

		orderInfoVO.setShop(shopList);

		/**
		 * 以下内容为新增部分
		 */
		// 优惠劵信息查询，当前用户在当前商家中可用的优惠劵
		Shop shop = shopDAO.query(shopId);
		List<UserCouponsInfoBO> couponsList = userCouponsDAO.getCouponsByShopId(userId, shop.getChainId(),shop.getId());

		coupons: for (int i = 0; i < couponsList.size(); i++) {
			UserCouponsInfoBO ucBO = couponsList.get(i);
			if (ucBO.getThreshold().equals(CouponFullSubtraction.UNRESTRICTED.toIntValue())) {
				continue;
			}
			if (ucBO.getPlatform().equals(CouponsPlatform.INTERNAL.toIntValue())) {
				if (ucBO.getFullPriceReduction() > sumPayMoney) {
					couponsList.remove(ucBO);
					continue;
				}
			} else {
				for (int t = 0; t < shopList.size(); t++) {
					OrdersShopVO sbo = shopList.get(t);
					if (sbo.getShopId().equals(ucBO.getShopId())) {
						if (ucBO.getThreshold().equals(CouponFullSubtraction.FULL_SUBTRACTION.toIntValue())) {
							if (ucBO.getFullPriceReduction() > sbo.getRealMoney()) {
								couponsList.remove(ucBO);
								continue coupons;
							}
						}
					}
				}
			}
		}
		orderInfoVO.setCouponsDetails(couponsService.formatCoupons(couponsList));
		/**
		 * 以上内容为新增部分
		 */
		/**
		 * 以下计算会员卡
		 */
		String[] goodsInfo = goodsArray[0].split("_");
		Shop shopInfo = shopDAO.query(goodsInfo[2]);
		if (shopInfo != null) {
			// 用户在该csId下的会员卡
			String csId = shopInfo.getChainId() == null ? shopInfo.getId() : shopInfo.getChainId();
			MemberCard memberCard = memberCardDAO.findAllByCsId(csId, userId);
			if (memberCard != null) {
				List<MemberCardUseVO> memberCardUseVOList = new ArrayList<MemberCardUseVO>();
				// 是否包邮
				if (memberCard.getIsFreeCarriage() == Is.YES.toIntValue()) {

					MemberCardUseVO vo = new MemberCardUseVO();
					vo.setPrivilegeType(MemberCardUseType.FREE_SHIPPING.toIntValue());
					vo.setPrivilegeMoney(orderInfoVO.getPostage());
					memberCardUseVOList.add(vo);
				}
				// 是否会员价
				if (memberCard.getIsDiscount() == Is.YES.toIntValue()) {
					Double discount = Format.decimal(
							orderInfoVO.getSumMoney() - orderInfoVO.getSumMoney() * (memberCard.getDiscount() / 10));

					MemberCardUseVO vo = new MemberCardUseVO();
					vo.setPrivilegeType(MemberCardUseType.DISCOUNT.toIntValue());
					vo.setPrivilegeMoney(discount);
					memberCardUseVOList.add(vo);
				}
				orderInfoVO.setMemberCardUseList(memberCardUseVOList);
			}
			ShopClient shopClient = shopClientDAO.findClientByUserId(userId, csId);
			orderInfoVO.setShopClient(shopClient);
		}

		// 地址
		Address address = addressDAO.getDefalutAddress(userId);
		if (address != null && StringUtils.isNotBlank(address.getId())) {
			AddressVO addressVO = new AddressVO();
			addressVO.setId(address.getId());
			addressVO.setName(address.getName());
			addressVO.setAddress(address.getAddress());
			addressVO.setArea(address.getArea());
			addressVO.setIsChecked(address.getIsChecked());
			addressVO.setPhone(address.getPhone());
			orderInfoVO.setAddress(addressVO);
		} else {
			result.setStatus(APICodeStatus.ADDRESS_IS_NULL);
			result.setMessage("Address is null.");
			orderInfoVO.setAddress(null);
		}
		orderInfoVO.setFoodBoxCharge(Format.decimal(foodBoxCharge));
		result.setData(orderInfoVO);
		return result;
	}

	@Override
	public ResultVO findShopOrderInfo(String userId, String goods) {
		ResultVO result = new ResultVO();
		OrderInfoVO orderInfoVO = new OrderInfoVO();

		List<OrderInfoGoodsVO> goodsList = new ArrayList<OrderInfoGoodsVO>();
		// 商品
		String[] goodsArray = goods.split(";");// number_goodsId_shopId_skuContentId
		Boolean isGoodsEmpty = true;
		Map<String, OrdersShopVO> shopIds = new HashMap<String, OrdersShopVO>();
		String shopId = "";
		// 餐盒费
		Double foodBoxCharge = new Double(0);
		try {
			for (int i = 0; i < goodsArray.length; i++) {
				String[] goodsInfo = goodsArray[i].split("_");

				Integer number = Integer.valueOf(goodsInfo[0]);
				GoodsBO goodsBO = null;
				if (goodsInfo.length == 4) {
					goodsBO = goodsDAO.getGoodsByBarcode(userId, goodsInfo[2], goodsInfo[1], goodsInfo[3]);// sku
				} else {
					goodsBO = goodsDAO.getGoodsInfo(userId, goodsInfo[2], goodsInfo[1]);// not
																						// sku
				}
				if ("" == shopId) {
					shopId = goodsInfo[2];
				}
				// shop info
				OrdersShopVO shopInfo = new OrdersShopVO();
				shopInfo.setShopId(goodsBO.getShopId());
				shopInfo.setShopName(goodsBO.getShopName());
				shopInfo.setShopLogo(goodsBO.getShopHeadImgUrl());
				shopInfo.setType(goodsBO.getShopType());
				shopIds.put(goodsInfo[2], shopInfo);

				// goods info
				if (goodsBO != null && StringUtils.isNotBlank(goodsBO.getId())) {
					OrderInfoGoodsVO orderInfoGoodsVO = new OrderInfoGoodsVO();
					BeanUtils.copyProperties(goodsBO, orderInfoGoodsVO);
					orderInfoGoodsVO.setNumber(number);
					foodBoxCharge += goodsBO.getFoodBoxCharge();
					goodsList.add(orderInfoGoodsVO);
					isGoodsEmpty = false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			isGoodsEmpty = true;
		}
		if (isGoodsEmpty) {
			result.setStatus(APICodeStatus.GOODS_NOT_FOUND);
			result.setMessage("Goods not found.");
			return result;
		}

		Double shopGoodMoney = 0.00;
		List<OrdersShopVO> shopList = new ArrayList<OrdersShopVO>();
		for (OrdersShopVO ordersShopVO : shopIds.values()) {
			Double shopPayMoney = 0.00;
			for (OrderInfoGoodsVO orderInfoGoodsVO : goodsList) {
				if (orderInfoGoodsVO.getShopId().equals(ordersShopVO.getShopId())) {
					ordersShopVO.addGoods(orderInfoGoodsVO);
					// 商品总价
					shopPayMoney += orderInfoGoodsVO.getPrice() * orderInfoGoodsVO.getNumber();

				}
			}
			ordersShopVO.setPayMoney(shopPayMoney);
			shopGoodMoney += shopPayMoney;
			shopList.add(ordersShopVO);
		}
		orderInfoVO.setShop(shopList);
		orderInfoVO.setSumMoney(shopGoodMoney);
		/**
		 * 以下内容为新增部分
		 */
		// 优惠劵信息查询，当前用户在当前商家中可用的优惠劵以及总部的优惠劵
		Shop shop = shopDAO.query(shopId);
		List<UserCouponsInfoBO> couponsList = userCouponsDAO.getCouponsByShopId(userId, shop.getChainId(),shop.getId());
		coupons: for (int i = 0; i < couponsList.size(); i++) {
			UserCouponsInfoBO ucBO = couponsList.get(i);
			if (ucBO.getThreshold().equals(CouponFullSubtraction.UNRESTRICTED.toIntValue())) {
				continue;
			}
			if (ucBO.getPlatform().equals(CouponsPlatform.INTERNAL.toIntValue())) {
				if (ucBO.getFullPriceReduction() > shopGoodMoney) {
					couponsList.remove(ucBO);
					continue;
				}
			} else {
				for (int t = 0; t < shopList.size(); t++) {
					OrdersShopVO sbo = shopList.get(t);
					if (sbo.getShopId().equals(ucBO.getShopId())) {
						if (ucBO.getThreshold().equals(CouponFullSubtraction.FULL_SUBTRACTION.toIntValue())) {
							if (ucBO.getFullPriceReduction() > sbo.getPayMoney()) {
								couponsList.remove(ucBO);
								continue coupons;
							}
						}
					}
				}
			}
		}
		orderInfoVO.setCouponsDetails(couponsService.formatCoupons(couponsList));
		/**
		 * 以上内容为新增部分
		 */
		/**
		 * 以下计算会员卡
		 */
		String[] goodsInfo = goodsArray[0].split("_");
		Shop shopInfo = shopDAO.query(goodsInfo[2]);
		if (shopInfo != null) {
			// 用户在该csId下的会员卡
			String csId = shopInfo.getChainId() == null ? shopInfo.getId() : shopInfo.getChainId();
			MemberCard memberCard = memberCardDAO.findAllByCsId(csId, userId);
			if (memberCard != null) {
				List<MemberCardUseVO> memberCardUseVOList = new ArrayList<MemberCardUseVO>();
				// 是否包邮
				if (memberCard.getIsFreeCarriage() == Is.YES.toIntValue()) {
					MemberCardUseVO vo = new MemberCardUseVO();
					vo.setPrivilegeType(MemberCardUseType.FREE_SHIPPING.toIntValue());
					vo.setPrivilegeMoney(orderInfoVO.getPostage());
					memberCardUseVOList.add(vo);
				}
				// 是否会员价
				if (memberCard.getIsDiscount() == Is.YES.toIntValue()) {
					Double discount = Format.decimal(
							orderInfoVO.getSumMoney() - orderInfoVO.getSumMoney() * (memberCard.getDiscount() / 10));

					MemberCardUseVO vo = new MemberCardUseVO();
					vo.setPrivilegeType(MemberCardUseType.DISCOUNT.toIntValue());
					vo.setPrivilegeMoney(discount);
					memberCardUseVOList.add(vo);
				}
				orderInfoVO.setMemberCardUseList(memberCardUseVOList);
			}
			ShopClient shopClient = shopClientDAO.findClientByUserId(userId, csId);
			orderInfoVO.setShopClient(shopClient);
		}
		orderInfoVO.setFoodBoxCharge(Format.decimal(foodBoxCharge));
		result.setData(orderInfoVO);
		return result;
	}

	@Override
	public ResultVO orderInfo(String orderId) {
		ResultVO result = new ResultVO();
		OrdersBO ordersBO = ordersDAO.findOrderId(orderId);
		if (ordersBO == null) {
			throw new OrdersNotFoundException("没找到订单");
		}
		List<OrdersGoodsBO> ordersGoodsBOList = ordersGoodsDAO.getOrderGoods(orderId);
		if (ordersGoodsBOList != null && ordersGoodsBOList.size() == 0) {
			throw new OrdersGoodsNotFoundException("订单商品没找到");
		}

		OrdersVO ordersVO = new OrdersVO();
		BeanUtils.copyProperties(ordersBO, ordersVO);
		List<OrdersGoodsVO> ordersGoodsVOList = new ArrayList<OrdersGoodsVO>();
		Double goodsPrice = 0.00;
		for (OrdersGoodsBO ordersGoodsBO : ordersGoodsBOList) {
			if (ordersGoodsBO.getPrice() != null) {
				goodsPrice += (ordersGoodsBO.getPrice() * ordersGoodsBO.getNumber());
			}
			OrdersGoodsVO ordersGoodsVO = new OrdersGoodsVO();
			BeanUtils.copyProperties(ordersGoodsBO, ordersGoodsVO);
			ordersGoodsVOList.add(ordersGoodsVO);
		}
		ordersVO.setGoodsPrice(Format.decimal(goodsPrice));
		ordersVO.setGoods(ordersGoodsVOList);
		ordersVO.setAddress(ordersBO.getArea() + " " + ordersBO.getAddress());

		List<MemberCardUseBO> memberCardUseList = memberCardUseDAO.getAllByOrderNumber(ordersBO.getOrderNumber());
		ordersVO.setMemberCardUseList(memberCardUseList);

		result.setData(ordersVO);
		return result;
	}

	@Override
	public ResultVO onlinePaySuccess(String orderNumber) {
		ResultVO result = new ResultVO();
		List<Orders> list = ordersDAO.getOrderByOrderNumber(orderNumber);
		if (list.size() < 0) {
			throw new OrdersNotFoundException("订单没找到");
		}
		OrdersPaySuccessVO ordersPaySuccessVO = new OrdersPaySuccessVO();
		Double payMoney = 0.00;
		for (Orders orders : list) {
			ordersPaySuccessVO.setShopOrderNumber(orders.getShopOrderNumber());
			ordersPaySuccessVO.setStatus(orders.getStatus());
			ordersPaySuccessVO.setOrderNumber(orders.getOrderNumber());
			ordersPaySuccessVO.setPayTime(orders.getPayTime());
			payMoney += orders.getPayMoney();
		}
		ordersPaySuccessVO.setPayMoney(Format.decimal(payMoney));
		result.setData(ordersPaySuccessVO);
		return result;
	}

	@Override
	public ResultVO offlinePaySuccess(String orderNumber) {
		ResultVO result = new ResultVO();
		OrdersBO ordersBO = ordersDAO.findOrderOffline(orderNumber);
		if (ordersBO == null) {
			throw new OrdersNotFoundException("订单没找到");
		}

		List<MemberCardUseBO> memberCardUseList = memberCardUseDAO.getAllByOrderNumber(ordersBO.getOrderNumber());

		OrdersPaySuccessVO ordersPaySuccessVO = new OrdersPaySuccessVO();
		BeanUtils.copyProperties(ordersBO, ordersPaySuccessVO);
		Double money = Format.decimal(ordersPaySuccessVO.getPrice() * ordersPaySuccessVO.getNumber());
		ordersPaySuccessVO.setGoodsMoney(money);
		ordersPaySuccessVO.setMemberCardUseList(memberCardUseList);
		// String validationCode = ordersPaySuccessVO.getValidationCode();
		// try {
		// String passwordKeyValue =
		// PropertiesUtil.getProperties(Constants.KEY_PROPERTIES_FOR_SYSTEM,
		// Constants.SYSTEM_KEY_FOR_PASSOWRD);
		// String sign = AESUtil.decrypt(validationCode, passwordKeyValue);
		// ordersPaySuccessVO.setValidationCode(sign);
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		result.setData(ordersPaySuccessVO);
		return result;
	}

	@Transactional
	public ResultVO createOrder(HttpServletRequest request, CreateOrderVO createOrderVO) {
		ResultVO result = new ResultVO();
		UserBO userBO = userDAO.findUserId(createOrderVO.getUserId());
		if (userBO == null || StringUtils.isBlank(userBO.getId())) {
			throw new UserNotFoundException("User not found");
		}
		// 可使用优惠劵的商品集合
		// List<Goods> goodsDiscount = new ArrayList<Goods>();
		// 可使用优惠劵商品及总价格集合
		// Map<String,Double> goodsDiscountMap = new HashMap<String,Double>();
		// 新增检验商品库存
		if (StringUtils.isNoneBlank(createOrderVO.getGoods())) {
			String goodsStr = createOrderVO.getGoods().replace(":", ";");
			String[] goodsArray = goodsStr.split(";");
			List<String> list = new ArrayList<>();
			for (int i = 0; i < goodsArray.length; i++) {
				String[] goodsObj = goodsArray[i].split("_");// number_price_goodsId_skuContentId
				Integer number = Integer.valueOf(goodsObj[0]);
				String goodsId = goodsObj[2];
				String skuContentId = "";
				if (goodsObj.length == 4) {
					skuContentId = goodsObj[3];
				}
				Integer stock = 0;
				Goods goods = goodsDAO.query(goodsId);
				if (goods == null) {
					throw new GoodsNotFoundException("商品没找到");
				}
				// if(goods.getIsOpenRebate() == Is.NO.toIntValue() &&
				// goods.getIsOpenSell() == Is.NO.toIntValue()){
				// goodsDiscount.add(goods);
				// Double total = number*Double.valueOf(goodsObj[1]);
				// goodsDiscountMap.put(goods.getId(), total);
				// }

				if (StringUtils.isNotBlank(skuContentId)) {
					SkuContent skuContent = skuContentDAO.query(skuContentId);
					if (skuContent == null) {
						throw new SkuContentNotFoundException("sku规格组合没找到");
					}
					stock = skuContent.getStock();
				} else {
					stock = goods.getStock();
				}
				if (number > stock) {
					list.add(goods.getName());
				}
			}
			if (list.size() > 0) {
				result.setData(list);
				result.setStatus(APICodeStatus.GOODS_UNDERSTOCK);
				result.setMessage("goods understock ");
				return result;
			}
		}
		// 将可使用优惠卷集合按照店铺分类好类
//		Map<String, Set<String>> shopGoodsMap = new HashMap<String, Set<String>>();
		// 得出店铺普通商品总价格
//		Map<String, Double> shopGoodsTotalMoney = new HashMap<String, Double>();
		// 普通商品交易总金额(只包含普通商品,可使用优惠劵的商品)
//		Double transactionTotalMoney = new Double(0);
		// for(int i = 0,t = goodsDiscount.size();i<t;i++){
		// Goods g = goodsDiscount.get(i);
		// String id = g.getId();
		// String shopId = g.getShopId();
		//
		// Double money = goodsDiscountMap.get(id);
		//
		// transactionTotalMoney += money;
		//
		// if(shopGoodsTotalMoney.containsKey(shopId)){
		// Double totalMoney = shopGoodsTotalMoney.get(shopId);
		// totalMoney += money;
		// shopGoodsTotalMoney.put(shopId, totalMoney);
		// }else{
		// shopGoodsTotalMoney.put(shopId, money);
		// }
		//
		// if(shopGoodsMap.containsKey(shopId)){
		// Set<String> set = shopGoodsMap.get(shopId);
		// set.add(id);
		// }else{
		// Set<String> set = new HashSet<String>();
		// set.add(id);
		// shopGoodsMap.put(shopId, set);
		// }
		// }

		Orders newOrder = new Orders();
		// 拆分前端传入各种参数
		String orderNumber = NumberUtils.getOrderlNumber();
		String[] shops = createOrderVO.getShopId().split(";");
		String[] realMoney = createOrderVO.getRealMoney().split("_");
		String[] postage = createOrderVO.getPostage().split("_");
		String[] payMoney = createOrderVO.getPayMoney().split("_");
		// 店铺优惠劵集合
		String[] coupons = createOrderVO.getUserCouponsIds().split(";");

		String[] discountMoney = createOrderVO.getDiscountMoney().split("_");
		// 商品ID集合 number_price_goodsId_skuContentId,number_price_goodsId_skuContentId:
		String[] goodsIds = createOrderVO.getGoods().split(":");
		// 店铺优惠劵(使用的优惠劵按照店铺分好类,由于限制一个店铺只能用一张优惠劵,所以一个店铺ID只对应了一个店铺优惠劵)
		Map<String, String> couponsMap = new HashMap<String, String>();
		// 此状态位标识是否是使用总部优惠劵，默认否。
		boolean isEquable = false;
		// 交易总金额(含分销返利)
		Double totalPayMoney = new Double(0);
		for (int i = 0; i < payMoney.length; i++) {
			String pay = payMoney[i];
			totalPayMoney += Double.parseDouble(pay);
		}
		// 如果有优惠劵则按照店铺、优惠劵存储。
		if (StringUtils.isNotBlank(createOrderVO.getUserCouponsIds())) {
			for (String s : coupons) {
				String[] src = s.split("_");
				if (src.length > 1) {
					couponsMap.put(src[0], src[1]);
				}
			}
		} else {
			isEquable = true;
		}
		// 实际交易总金额(用于最后发起微信支付)
		Double totalFee = 0.0;

		// 用户在该csId下的会员卡
		MemberCard memberCard = memberCardDAO.findAllByCsId(createOrderVO.getCsId(), userBO.getId());

		for (int i = 0, t = shops.length; i < t; i++) {
			String shopIds = shops[i];
			Orders order = new Orders();
			order.setShopId(shopIds);
			order.setUserId(createOrderVO.getUserId());
			order.setAddressId(createOrderVO.getAddressId());
			order.setOrderNumber(orderNumber);// 总订单号
			order.setShopOrderNumber(NumberUtils.getOrderlNumber());// 店铺订单号
			order.setRealMoney(Double.valueOf(realMoney[i]));// 优惠前金额
			order.setPostage(Double.valueOf(postage[i]));// 运费
			order.setPayMoney(Double.valueOf(payMoney[i]));// 支付金额未优惠
			order.setStatus(OrderStatus.WAIT.toIntValue());
			order.setRemark(createOrderVO.getRemark());
			order.setType(createOrderVO.getType());
			
			if (shops.length >= 1) {
				order.setDeductionMoney(createOrderVO.getDeductionMoney());
			} else {
				order.setDeductionMoney(
						Double.valueOf(payMoney[i]) / totalPayMoney * createOrderVO.getDeductionMoney());
			}
			// 以下过程设置优惠金额
			// if (isEquable) {
			// //取出店铺所有普通商品的支付金额
			// Double shoptotalPayMoney = shopGoodsTotalMoney.get(shopIds);
			// if(shoptotalPayMoney == null){
			// shoptotalPayMoney = new Double(0);
			// }
			// // 店铺所有普通商品的支付金额/所有普通商品支付金额*总部优惠金额(如果没有使用总部优惠卷则这里总部优惠卷取出的是0)
			// Double ratio = (shoptotalPayMoney / transactionTotalMoney) *
			// createOrderVO.getInternalDiscountMoney();
			// ratio = Format.decimal(ratio);
			// //存入的是普通商品被优惠的金额
			// order.setCouponsMoney(ratio);
			// order.setUserCouponsId(createOrderVO.getInternalDiscountId());
			// } else {
			// //discountMoney 存的是普通商品被优惠的金额，如果该店铺没有用优惠劵则此处应该为0
			// order.setCouponsMoney(Double.parseDouble(discountMoney[i]));
			// order.setUserCouponsId(couponsMap.get(shopIds));
			// }
			// 以下过程设置优惠金额
			if (isEquable) {
				// 取出店铺所有普通商品的支付金额
				// Double shoptotalPayMoney = shopGoodsTotalMoney.get(shopIds);
				// if(shoptotalPayMoney == null){
				// shoptotalPayMoney = new Double(0);
				// }
				// 店铺所有普通商品的支付金额/所有普通商品支付金额*总部优惠金额(如果没有使用总部优惠卷则这里总部优惠卷取出的是0)

				// 店铺优惠前金额/总支付金额*总部优惠金额(如果没有使用总部优惠卷则这里总部优惠卷取出的是0)
				Double ratio = (order.getRealMoney() / totalPayMoney) * createOrderVO.getInternalDiscountMoney();
				ratio = Format.decimal(ratio);
				// 存入的是普通商品被优惠的金额
				order.setCouponsMoney(ratio);
				order.setUserCouponsId(createOrderVO.getInternalDiscountId());
			} else {
				// discountMoney 如果该店铺没有用优惠劵则此处应该为0
				order.setCouponsMoney(Double.parseDouble(discountMoney[i]));
				order.setUserCouponsId(couponsMap.get(shopIds));
			}
			// 会员卡会员价金额
			Double discount = 0.0;
			// 取出会员卡信息
			//会员价使用记录对象
			MemberCardUse memberCardUseMember = null;
			//包邮使用记录对象
			MemberCardUse memberCardUsePostage = null;
			if (memberCard != null) {
				// 是否包邮
				if (memberCard.getIsFreeCarriage() == Is.YES.toIntValue()) {
					memberCardUsePostage = new MemberCardUse();
					memberCardUsePostage.setCsId(createOrderVO.getCsId());
					memberCardUsePostage.setUserId(userBO.getId());
					memberCardUsePostage.setOrderId(orderNumber);
					memberCardUsePostage.setMemberCardId(memberCard.getId());
					memberCardUsePostage.setPrivilegeType(MemberCardUseType.FREE_SHIPPING.toIntValue());
					memberCardUsePostage.setPrivilegeMoney(order.getPostage());
					order.setPostage(0.0);
				}
				// 是否会员价
				if (memberCard.getIsDiscount() == Is.YES.toIntValue()) {

					discount = Format
							.decimal(order.getPayMoney() - order.getPayMoney() * (memberCard.getDiscount() / 10));
					
					memberCardUseMember = new MemberCardUse();
					memberCardUseMember.setCsId(createOrderVO.getCsId());
					memberCardUseMember.setUserId(userBO.getId());
					memberCardUseMember.setOrderId(orderNumber);
					memberCardUseMember.setMemberCardId(memberCard.getId());
					memberCardUseMember.setPrivilegeType(MemberCardUseType.DISCOUNT.toIntValue());
					memberCardUseMember.setPrivilegeMoney(discount);

				}
			}
			//餐盒费
			Double foodBoxCharge = createOrderVO.getFoodBoxCharge() == null?0:createOrderVO.getFoodBoxCharge();
			order.setFoodBoxCharge(Format.decimal(foodBoxCharge));
			// 重新计算支付金额(减去优惠金额,减去抵扣金额,减去会员价金额,加上运费,加上餐盒费)
			Double operation = order.getPayMoney() - order.getCouponsMoney() - order.getDeductionMoney() - discount + order.getFoodBoxCharge();
			
			if (operation < 0) {
				operation = 0.0;
			}
			Double finalPayMoney = Format.decimal(operation + order.getPostage());

			if (finalPayMoney < 0) {
				finalPayMoney = 0.0;
			}

			order.setPayMoney(finalPayMoney);

			order.setPayWay(PayWay.toValue(createOrderVO.getPayWay()).toIntValue());

			if (createOrderVO.getType() == OrderType.EXTRACT.toIntValue()) {
				order.setConsumeName(createOrderVO.getConsumeName());
				order.setConsumePhone(createOrderVO.getConsumePhone());
			}

			if (createOrderVO.getType() == OrderType.EAT.toIntValue()) {
				String tableNumber = createOrderVO.getTableNumber() == null ? "" : createOrderVO.getTableNumber();
				try {
					tableNumber = URLDecoder.decode(tableNumber, "gbk");
					tableNumber = new String(tableNumber.getBytes(),"utf-8");
				} catch (UnsupportedEncodingException e) {
					logger.info(e.getMessage());
					e.printStackTrace();
				}
				order.setTableNumber(tableNumber);
			}

			newOrder = ordersDAO.insert(order);
			
			if(memberCardUseMember!=null){
				memberCardUseMember.setOrderId(newOrder.getId());
				memberCardUseMember.setOrderNumber(orderNumber);
				memberCardUseDAO.insert(memberCardUseMember);
			}
			if(memberCardUsePostage!=null){
				memberCardUsePostage.setOrderId(newOrder.getId());
				memberCardUsePostage.setOrderNumber(orderNumber);
				memberCardUseDAO.insert(memberCardUsePostage);
			}

			if (couponsMap.containsKey(shopIds)) {
				String userCoupons = couponsMap.remove(shopIds);
				couponsMap.put(newOrder.getId(), userCoupons);
			}

			totalFee += newOrder.getPayMoney();

			ordersGoodsService.add(goodsIds[i], newOrder.getId(), createOrderVO.getUserId(), shopIds);
		}
		// 清理不需要的对象
		// goodsDiscount.clear();
		// goodsDiscountMap.clear();
//		shopGoodsMap.clear();
//		shopGoodsTotalMoney.clear();

		// 更新优惠劵信息
		if (couponsMap.size() > 0) {
			userCouponsService.handleUserCoupons(couponsMap);
		} else {
			if (StringUtils.isNoneBlank(createOrderVO.getInternalDiscountId())) {
				userCouponsService.handleUserCoupons(newOrder.getOrderNumber(), createOrderVO.getInternalDiscountId());
			}
		}

		// 删除购物车的商品
		if (StringUtils.isNoneBlank(createOrderVO.getCartIds())) {
			cartDAO.batchDeleteGoods(createOrderVO.getCartIds().split(","));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderNumber", orderNumber);
		map.put("orderId", newOrder.getId());
		map.put("shopOrderNumber", newOrder.getShopOrderNumber());
		if (totalFee > 0 && createOrderVO.getPayWay() == PayWay.WECHAT.toIntValue()) {
			// 发起微信支付申请
			String wechatKey = DIYKey.getWechatCodeKey(createOrderVO.getWcId());
			WechatConfig wechatConfig = wechatConfigCacheDAO.getHash(wechatKey, WechatConfig.class);
			if (wechatConfig == null) {
				wechatConfig = wechatConfigDAO.getWechatConfigByWcId(createOrderVO.getWcId());
				boolean is = wechatConfigCacheDAO.addHash(wechatKey, wechatConfig);
				if (!is) {
					throw new WechatConfigAddException("找不到微信配置");
				}
			}

			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setAttach(newOrder.getId());
			orderInfo.setOutTradeNo(orderNumber);
			orderInfo.setBody(WECHAT_BODY_KEY + "-" + orderNumber);
			orderInfo.setTotalFee(Math.round(totalFee * 100));
			orderInfo.setSpbillCreateIp(RequestUtil.getRealIp(request));
			orderInfo.setOpenId(userBO.getOpenId());
			orderInfo.setTradeType(createOrderVO.getTradeType());
			PayParam payParam = WeChatUtils.getPayParam(orderInfo, wechatConfig);
			logger.error("form_id>>>>>>>>>>>>>>>>>>" + payParam.getFormId());
			if (StringUtils.isNoneBlank(payParam.getFormId())) {
				String key = DIYKey.getFormIdByOrderNumber(orderNumber);
				UserFormIdVO userFormIdVO = new UserFormIdVO();
				userFormIdVO.setUserId(userBO.getId());
				userFormIdVO.setFormId(payParam.getFormId());
				userFormIdVO.setEndTime(DateUtil.addDays(new Date(), 7));
				userCacheDAO.addHash(key, userFormIdVO);
			}
			map.put("patParam", payParam);
		} else {
			
			List<Orders> list = ordersDAO.getOrderByPay(userBO.getId(), orderNumber);
			for (Orders orders : list) {
				if (list.size() < 0)
					throw new OrderNotFoundException("Orders not found");
				// Double couponsMoney = 0.0;
				// 实付金额
				Double realPay = orders.getPayMoney() == null ? 0.0 : orders.getPayMoney();
				// couponsMoney += orders.getCouponsMoney();
				String userId = userBO.getId();
				orders.setTransactionNumber(null);
				orders.setPayTime( new Date());
				orders.setPayWay(createOrderVO.getPayWay());
				if(createOrderVO.getType() == OrderType.EAT.toIntValue()){
					orders.setStatus(OrderStatus.COMPLETE.toIntValue());
				}else{
					orders.setStatus(OrderStatus.PAID.toIntValue());
				}
				
				ordersDAO.update(orders);

				// 检查是否满足享有二级分润条件
				SystemConfig systemConfig = systemConfigDAO.find();
				if (systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()) {
					Double value = ordersDAO.sumPayMoney(userId);
					if (value >= systemConfig.getSellValue()) {
						User userParams = userDAO.query(userId);
						userParams.setIsMemberSell(Is.YES.toIntValue());
						userDAO.update(userParams);
					}
				}

				OrdersDataHistory ordersDataHistory = new OrdersDataHistory();
				ordersDataHistory.setOrdersId(orders.getId());
				ordersDataHistory.setShopId(orders.getShopId());
				ordersDataHistory.setOrderNumber(orders.getOrderNumber());
				ordersDataHistory.setShopOrderNumber(orders.getShopOrderNumber());
				ordersDataHistory.setRealMoney(orders.getRealMoney());
				ordersDataHistory.setTransactionNumber(orders.getTransactionNumber());
				ordersDataHistory.setPayMoney(orders.getPayMoney());
				ordersDataHistory.setPostage(orders.getPostage());
				ordersDataHistory.setStatus(OrdersDataHistoryStatus.CLOSE.toIntValue());
				UserCoupons userCoupons = userCouponsDAO.getUserCoupons(userId, orders.getId(), orderNumber);
				if (userCoupons != null) {
					ordersDataHistory.setCouponsId(orders.getUserCouponsId());
					ordersDataHistory.setCouponsType(userCoupons.getCouponsType());
					if (userCoupons.getCouponsType() == CouponsType.SHOP.toIntValue()) {
						ordersDataHistory.setCouponsMoney(orders.getCouponsMoney());
					} else {
						Double avg = orders.getPayMoney() / realPay * orders.getCouponsMoney();
						ordersDataHistory.setCouponsMoney(Format.decimal(avg));
					}
				}
				OrdersDataHistory ordersDataHistoryparams = ordersDataHistoryDAO.insert(ordersDataHistory);

				int number = 0;
				List<OrdersGoods> ordersGoodsList = ordersGoodsDAO.getOrderGoodsByOrderId(orders.getId());
				for (OrdersGoods ordersGoods : ordersGoodsList) {

					number += ordersGoods.getNumber();
					Goods goods = goodsDAO.query(ordersGoods.getGoodsId());
					if (goods.getIsOpenSku() == Is.YES.toIntValue()) {
						SkuContent skuContent = skuContentDAO.query(ordersGoods.getSkuContentId());
						skuContent.setStock(skuContent.getStock() - ordersGoods.getNumber());// 库存
						skuContentDAO.update(skuContent);

						// 添加待结算金额
						Shop shop = shopDAO.query(goods.getShopId());
						Double sumGoodsMoney = skuContent.getPrice() * ordersGoods.getNumber();
						Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() / 100);
						if (goods.getIsOpenRebate() == Is.YES.toIntValue()
								&& goods.getIsOpenSell() == Is.YES.toIntValue()) {
							shop.setAccumulativeMoney(shop.getAccumulativeMoney() + waitSumMoney);
							shop.setMonthIncomeMoney(shop.getMonthIncomeMoney() + waitSumMoney);
							shop.setWithdrawalMoney(shop.getWithdrawalMoney() + waitSumMoney);
						} else {
							shop.setWaitSumMoney(shop.getWaitSumMoney() + waitSumMoney);
						}
						shopDAO.update(shop);

						OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
						Industry industry = industryDAO.query(shop.getIndustryId());
						dataHistory.setShopMoney(dataHistory.getShopMoney() + waitSumMoney);
						dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
						dataHistory.setIndustryFullName(industry.getName());
						ordersDataHistoryDAO.update(dataHistory);

						GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
						goodsDataHistory.setGoodsId(goods.getId());
						goodsDataHistory.setShopId(goods.getShopId());
						goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
						goodsDataHistory.setTypeId(goods.getTypeId());
						goodsDataHistory.setGoodsName(goods.getName());
						goodsDataHistory.setSkuContentName(skuContent.getStandards());
						goodsDataHistory.setNumber(ordersGoods.getNumber());
						goodsDataHistory.setPrice(skuContent.getPrice());
						goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
						goodsDataHistory.setProfit(goods.getProfit());
						goodsDataHistory.setShopMoney(waitSumMoney);
						goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
						goodsDataHistory .setCouponsMoney(Format.decimal(sumGoodsMoney / orders.getPayMoney() * dataHistory.getCouponsMoney()));
						GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);

						// 有SKU商品进入排队返利队列
						if (goods.getIsOpenRebate() == Is.YES.toIntValue()) {
							for (int i = 0; i < ordersGoods.getNumber(); i++) {

								RebateVO rebateVO = new RebateVO();
								rebateVO.setGoodsId(goods.getId());
								rebateVO.setSkuContentId(skuContent.getId());
								rebateVO.setPrice(skuContent.getPrice());
								rebateVO.setShopId(goods.getShopId());
								rebateVO.setUserId(userId);
								rebateVO.setOrderId(ordersGoods.getOrderId());
								rebateVO.setGoodsName(goods.getName());
								rebateVO.setOrderGoodsId(ordersGoods.getId());
								RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
								if (StringUtils.isNoneBlank(rebateInfo.getId())) {
									rebateService.updateRedate(rebateInfo);
								}
							}
						}

						if (goods.getIsOpenSell() == Is.YES.toIntValue()
								&& goods.getIsOpenSell() == Is.YES.toIntValue()) {
							// 分销
							commissionHistoryService.add(userId, ordersGoods.getId(), userBO.getParentId(),
									ordersDataHistoryparams.getId(), goodsDataHistoryParam.getId());
						}

						goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
						Double profit = (goodsDataHistory.getPrice() * goodsDataHistory.getNumber())
								- goodsDataHistory.getShopMoney(); // 利润
						// 共分出多少钱
						Double sumMoney = goodsDataHistory.getReferrerMoney()
								+ goodsDataHistory.getPrimaryBenefitMoney() + goodsDataHistory.getSecondBenefitMoney()
								+ goodsDataHistory.getShopGetBenefitMoney();
						Double grossMargin = profit - sumMoney; // 毛利
						Double grossMarginRate = grossMargin / profit * 100;// 毛利率
						if (!grossMarginRate.isNaN()) {
							goodsDataHistory.setGrossMargin(grossMargin);
							goodsDataHistory.setGrossMarginRate(grossMarginRate);
						}
						goodsDataHistoryDAO.update(goodsDataHistory);
					} else {
						goods.setStock(goods.getStock() - ordersGoods.getNumber());// 库存

						// 添加待结算金额
						Shop shop = shopDAO.query(goods.getShopId());
						Double sumGoodsMoney = goods.getPrice() * ordersGoods.getNumber();
						Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() / 100);
						if (goods.getIsOpenRebate() == Is.YES.toIntValue()
								&& goods.getIsOpenSell() == Is.YES.toIntValue()) {
							shop.setAccumulativeMoney(shop.getAccumulativeMoney() + waitSumMoney);
							shop.setMonthIncomeMoney(shop.getMonthIncomeMoney() + waitSumMoney);
							shop.setWithdrawalMoney(shop.getWithdrawalMoney() + waitSumMoney);
						} else {
							shop.setWaitSumMoney(shop.getWaitSumMoney() + waitSumMoney);
						}
						shopDAO.update(shop);

						OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
						Industry industry = industryDAO.query(shop.getIndustryId());
						dataHistory.setShopMoney(dataHistory.getShopMoney() + waitSumMoney);
						dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
						dataHistory.setIndustryFullName(industry.getName());
						ordersDataHistoryDAO.update(dataHistory);

						GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
						goodsDataHistory.setGoodsId(goods.getId());
						goodsDataHistory.setShopId(goods.getShopId());
						goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
						goodsDataHistory.setTypeId(goods.getTypeId());
						goodsDataHistory.setGoodsName(goods.getName());
						goodsDataHistory.setNumber(ordersGoods.getNumber());
						goodsDataHistory.setPrice(goods.getPrice());
						goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
						goodsDataHistory.setProfit(goods.getProfit());
						goodsDataHistory.setShopMoney(waitSumMoney);
						goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
						goodsDataHistory.setCouponsMoney(
								Format.decimal(sumGoodsMoney / totalPayMoney * dataHistory.getCouponsMoney()));
						GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);

						// 没有SKU商品进入排队返利队列
						if (goods.getIsOpenRebate() == Is.YES.toIntValue()) {
							for (int i = 0; i < ordersGoods.getNumber(); i++) {
								RebateVO rebateVO = new RebateVO();
								rebateVO.setGoodsId(goods.getId());
								rebateVO.setPrice(goods.getPrice());
								rebateVO.setShopId(goods.getShopId());
								rebateVO.setUserId(userId);
								rebateVO.setGoodsName(goods.getName());
								rebateVO.setOrderId(ordersGoods.getOrderId());
								rebateVO.setOrderGoodsId(ordersGoods.getId());
								RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
								if (StringUtils.isNoneBlank(rebateInfo.getId())) {
									rebateService.updateRedate(rebateInfo);
								}
							}
						}
						if (goods.getIsOpenSell() == Is.YES.toIntValue()
								&& goods.getIsOpenSell() == Is.YES.toIntValue()) {
							// 分销
							commissionHistoryService.add(userId, ordersGoods.getId(), userBO.getParentId(),
									ordersDataHistoryparams.getId(), goodsDataHistoryParam.getId());
						}

						goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
						Double profit = (goodsDataHistory.getPrice() * goodsDataHistory.getNumber())
								- goodsDataHistory.getShopMoney(); // 利润
						// 共分出多少钱
						Double sumMoney = goodsDataHistory.getReferrerMoney()
								+ goodsDataHistory.getPrimaryBenefitMoney() + goodsDataHistory.getSecondBenefitMoney()
								+ goodsDataHistory.getShopGetBenefitMoney();
						Double grossMargin = profit - sumMoney; // 毛利
						Double grossMarginRate = grossMargin / profit * 100;// 毛利率
						if (!grossMarginRate.isNaN()) {
							goodsDataHistory.setGrossMargin(grossMargin);
							goodsDataHistory.setGrossMarginRate(grossMarginRate);
						}
						goodsDataHistoryDAO.update(goodsDataHistory);
					}

					goods.setSalesVolume(goods.getSalesVolume() + ordersGoods.getNumber());// 销量
					goodsDAO.update(goods);

					// 生成购买记录
					UserGoods userGoods = new UserGoods();
					userGoods.setShopId(orders.getShopId());
					userGoods.setGoodsId(ordersGoods.getGoodsId());
					userGoods.setUserId(userBO.getId());
					userGoods.setType(UserGoodsType.BUY.toIntValue());
					userGoods.setNumber(ordersGoods.getNumber());
					userGoodsDAO.insert(userGoods);

					// 统计订单数据表毛利
					OrdersDataHistory newOrdersDataHistory = ordersDataHistoryDAO
							.query(ordersDataHistoryparams.getId());
					if (newOrdersDataHistory != null) {
						Double profit = newOrdersDataHistory.getPayMoney() - newOrdersDataHistory.getPostage()
								- newOrdersDataHistory.getShopMoney();
						Double sumMoney = newOrdersDataHistory.getShareBenefitMoney()
								+ newOrdersDataHistory.getReferrerMoney() + newOrdersDataHistory.getAgencyBenefit()
								+ newOrdersDataHistory.getAgencyAccount();
						Double grossMargin = profit - sumMoney; // 毛利
						Double grossMarginRate = grossMargin / profit * 100;// 毛利率
						if (!grossMarginRate.isNaN()) {
							newOrdersDataHistory.setGrossMargin(grossMargin);
							newOrdersDataHistory.setGrossMarginRate(grossMarginRate);
						}
						ordersDataHistoryDAO.update(newOrdersDataHistory);
					}
				}

				// 添加交易记录
				PayHistory payHistory = new PayHistory();
				payHistory.setShopId(orders.getShopId());
				payHistory.setUserId(userId);
				/* 此处改动 */
				payHistory.setMoney(realPay);
				payHistory.setShopOrderNumber(orders.getShopOrderNumber());
				payHistory.setOrderNumber(orders.getOrderNumber());
				payHistory.setType(PayHistoryType.BUY.toIntValue());
				payHistory.setWay(createOrderVO.getPayWay());
				payHistoryDAO.insert(payHistory);

				// 插入交易记录
				TransactionAddVO transactionAddVO = new TransactionAddVO();
				BeanUtils.copyProperties(orders, transactionAddVO);
				transactionAddVO.setOrderId(orders.getId());
				transactionAddVO.setOrderType(orders.getType());
				transactionAddVO.setType(TransactionType.PAY.toIntValue());
				transactionAddVO.setNumber(number);
				transactionService.add(transactionAddVO);
			}

			if (createOrderVO.getPayWay() == PayWay.WECHAT.toIntValue()) {
				// 如果支付金额小于0则不发起微信支付，直接更新掉订单状态。
				if (createOrderVO.getType() == OrderType.EAT.toIntValue()) {
					this.changeStatus(newOrder.getId(), OrderStatus.COMPLETE.toIntValue());
					printingService.printIndex(newOrder.getShopId(), newOrder.getId());
				}else if(createOrderVO.getType() == OrderType.EXTRACT.toIntValue()){
					printingService.printIndex(newOrder.getShopId(), newOrder.getId());
					this.changeStatus(newOrder.getId(), OrderStatus.PAID.toIntValue());
				}else if(createOrderVO.getType() == OrderType.DELIVERY.toIntValue()){
					printingService.printIndex(newOrder.getShopId(), newOrder.getId());
					this.changeStatus(newOrder.getId(), OrderStatus.PAID.toIntValue());
				}else{
					this.changeStatus(newOrder.getId(), OrderStatus.PAID.toIntValue());
				}
				map.put("patParam", null);
				totalFee = 0.0;
			} else if (createOrderVO.getPayWay() == PayWay.MEMBER.toIntValue()) {
				// 使用会员卡支付
				ShopClient shopClient = shopClientDAO.findClientByUserId(userBO.getId(), createOrderVO.getCsId());
				if (shopClient.getBalance() > totalFee) {
					Double balance = Format.decimal(shopClient.getBalance() - totalFee);
					shopClient.setBalance(balance);
					boolean boo = shopClientDAO.update(shopClient);
					if (boo) {
						if (createOrderVO.getType() == OrderType.EAT.toIntValue()) {
							this.changeStatus(newOrder.getId(), OrderStatus.COMPLETE.toIntValue());
							printingService.printIndex(newOrder.getShopId(), newOrder.getId());
						}else if(createOrderVO.getType() == OrderType.EXTRACT.toIntValue()){
							printingService.printIndex(newOrder.getShopId(), newOrder.getId());
							this.changeStatus(newOrder.getId(), OrderStatus.PAID.toIntValue());
						}else if(createOrderVO.getType() == OrderType.DELIVERY.toIntValue()){
							printingService.printIndex(newOrder.getShopId(), newOrder.getId());
							this.changeStatus(newOrder.getId(), OrderStatus.PAID.toIntValue());
						}else{
							this.changeStatus(newOrder.getId(), OrderStatus.PAID.toIntValue());
						}
						map.put("patParam", null);
						totalFee = 0.0;
					}
				} else {
					throw new BalanceInsufficientException("余额不足");
				}
			}
			// 升级会员卡
			Shop csShop = shopDAO.query(newOrder.getShopId());
			String csId = csShop.getIsChain() == IsChainStatus.YES.toIntStatus() ? csShop.getChainId()
					: csShop.getId();
			if(StringUtils.isNotBlank(csId)){
				memberCardService.receiveByShop(createOrderVO.getUserId(), csId, csShop.getIsChain());
			}else{
				throw new ChainShopException("csId is required.");
			}
		}
		map.put("payMoney", totalFee);
		result.setData(map);
		return result;
	}

	public ResultVO createQRCode(String userId, String orderNumber) {
		ResultVO result = new ResultVO();
		List<Orders> list = ordersDAO.getOrderByPay(userId, orderNumber);
		if (list.size() < 0) {
			throw new OrdersNotFoundException("Order not found");
		}
		for (Orders orders : list) {
			String qrcodeName = orders.getId() + "." + FileUtil.QR_CODE_FORMAT;
			String fullpath = dataQrcodePath + qrcodeName;
			File file = new File(fullpath);
			if (file.exists())
				FileUtil.removeFile(fullpath);
			String qrCodeNumber = OrderNumberUtils.getOrderQrCodeNumber();
			FileUtil.createQRCode(qrCodeNumber, fullpath);
			
			try {
				AliyunOSSClientUtil.uploadObject2OSS(new FileInputStream(new File(dataQrcodePath+qrcodeName)) , qrcodeName, backetName, qrcodePath);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			orders.setQrCode(qrcodeName);
			orders.setValidationCode(qrCodeNumber);
			orders.setStatus(OrderStatus.WAITUSE.toIntValue());
			ordersDAO.update(orders);

			// 检查是否满足享有二级分润条件
			SystemConfig systemConfig = systemConfigDAO.find();
			if (systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()) {
				Double value = ordersDAO.sumPayMoney(userId);
				if (value >= systemConfig.getSellValue()) {
					User userParams = userDAO.query(userId);
					userParams.setIsMemberSell(Is.YES.toIntValue());
					userDAO.update(userParams);
				}
			}
		}

		return result;
	}

	@Override
	public int orderTotalCount(String userId) {
		return ordersDAO.orderTotalCount(userId);
	}

	// 微信支付成功后
	@Transactional
	public String getWechatNotify(String xml) {
		try {
			Map<String, String> msgObj = MessageUtil.parseXml(xml);
			String openId = msgObj.get("openid");
			String timeEnd = msgObj.get("time_end");
			String transactionNumber = msgObj.get("transaction_id");
			String totalFee = msgObj.get("total_fee");
			String orderNumber = msgObj.get("out_trade_no");
			String attach = msgObj.get("attach");

			/*
			 * String openId = "oZrh35PD5OaAorinW9auGQa1xUBk"; String timeEnd =
			 * "2018-08-15 16:06:00"; String transactionNumber =
			 * "5085134296797892"; String totalFee = "20"; String orderNumber =
			 * "5085134296797892"; String attach =
			 * Constants.WECHAT_ATTACH_FOR_BALANCE_HISTORY;
			 */

			User user = userDAO.checkOpenId(openId);
			Double payMoney = 0.0;
			Double couponsMoney = 0.0;
			if (StringUtils.isNotBlank(totalFee))
				payMoney = Double.valueOf(totalFee);
			payMoney = payMoney / 100;

			if (attach.equals(Constants.WECHAT_ATTACH_FOR_LOGISTICS)) {
				if (user == null || StringUtils.isBlank(user.getId()))
					throw new UserNotFoundException("User not found");

			} else if (attach.equals(Constants.WECHAT_ATTACH_FOR_RECHARGE)) {

				/*
				 * Recharge recharge = rechargeDAO.getRecharge(member.getId(),
				 * orderNumber); if(recharge != null &&
				 * StringUtils.isNotBlank(recharge.getId())){ MemberConfig
				 * memberConfig =
				 * memberConfigDAO.getMemberConfig(member.getId());
				 * if(memberConfig!=null &&
				 * StringUtils.isNotBlank(memberConfig.getId())){ //更新用户金额
				 * memberConfig.setCurrentMoney(memberConfig.getCurrentMoney()+
				 * recharge.getMoney());
				 * memberConfig.setPileMoney(memberConfig.getPileMoney()+
				 * recharge.getMoney()); memberConfigDAO.update(memberConfig); }
				 * } //更新充值记录 recharge.setMoney(recharge.getMoney());
				 * recharge.setPayMoney(recharge.getPayMoney());
				 * recharge.setStatus(RechargeStatus.SUCCEED.toIntStatus());
				 * rechargeDAO.update(recharge);
				 */
			}else if (attach.equals(Constants.WECHAT_ATTACH_FOR_BOOKING)) {
				//预约金支付
				Booking booking = bookingDAO.getByBookingNumber(orderNumber);
				if(booking == null){
					throw new NotFoundException("payment callback: booking not found.");
				}
				booking.setStatus(BookingStatus.CONFIRM.toIntValue());
				booking.setTransactionNumber(transactionNumber);
				booking.setPayTime(new Date());
				bookingDAO.update(booking);
				
			} else if (attach.equals(Constants.WECHAT_ATTACH_FOR_BALANCE_HISTORY)) {
				// 会员卡储值
				BalanceHistory balanceHistory = balanceHistoryDAO.getByOrderNumber(orderNumber);

				// 在商户会员表中修改记录
				ShopClient shopClient = shopClientDAO.findClientByUserId(balanceHistory.getUserId(),
						balanceHistory.getCsId());

				Double balance = shopClient.getBalance();

				balance += balanceHistory.getBalanceChange();

				if (balanceHistory.getCouponsId() != null) {
					couponsService.insert(balanceHistory.getUserId(), balanceHistory.getCouponsId());
				}

				if (balanceHistory.getGiveIntegral() != null) {
					Integer nowIntegral = shopClient.getNowIntegral();

					nowIntegral += balanceHistory.getGiveIntegral();

					shopClient.setNowIntegral(nowIntegral);
				}

				if (balanceHistory.getGiveMoney() != null) {
					balance += balanceHistory.getGiveMoney();

					BalanceHistory giveMoneyBalanceHistory = new BalanceHistory();
					giveMoneyBalanceHistory.setOrderNumber(orderNumber);
					giveMoneyBalanceHistory.setClientId(shopClient.getId());
					giveMoneyBalanceHistory.setCsId(balanceHistory.getCsId());
					giveMoneyBalanceHistory.setUserId(balanceHistory.getUserId());

					giveMoneyBalanceHistory.setOperation(BalanceHistoryOperation.STORAGE_VALUE.toIntValue());
					giveMoneyBalanceHistory.setStatus(BalanceHistoryStatus.ALREADY_PAID.toIntValue());
					giveMoneyBalanceHistory.setBalanceChange(balanceHistory.getGiveMoney());

					balanceHistoryDAO.insert(giveMoneyBalanceHistory);
				}

				shopClient.setBalance(balance);

				balanceHistory.setStatus(BalanceHistoryStatus.ALREADY_PAID.toIntValue());
				balanceHistory.setTransactionNumber(transactionNumber);
				shopClientDAO.update(shopClient);

				balanceHistoryDAO.update(balanceHistory);
			} else if (attach.equals(Constants.WECHAT_ATTACH_FOR_MEMBER_CARD)) {

				MemberCardHistory memberCardHistory = memberCardHistoryDAO.queryByOrderNumber(orderNumber);

				ShopClient shopClient = shopClientDAO.query(memberCardHistory.getShopClientId());

				MemberCard memberCard = memberCardDAO.query(memberCardHistory.getMemberCardId());

				Date now = new Date();

				shopClient.setMemberCardId(memberCard.getId());
				shopClient.setClientDate(now);
				if (memberCard.getValidTimeState() == MemberCardValidTime.FIXED.toIntStatus()) {
					shopClient.setMemberDate(memberCard.getValidStartTime());
					shopClient.setMemberEndDate(memberCard.getValidEndTime());
				} else if (memberCard.getValidTimeState() == MemberCardValidTime.PERIOD.toIntStatus()) {
					shopClient.setMemberDate(now);
					Date date = DateUtil.addDays(now, memberCard.getValidDays());
					shopClient.setMemberEndDate(date);
				} else {
					shopClient.setMemberDate(null);
					shopClient.setMemberEndDate(null);
				}
				shopClient.setClientStatus(ShopClientStatus.MEMBER.toIntStatus());
				shopClient.setGrade(memberCard.getCardGrade());
				if (memberCard.getIsPresentCoupon() == Is.YES.toIntValue()) {
					if (memberCard.getCouponsId() != null) {
						try {
							couponsService.insert(shopClient.getUserId(), memberCard.getCouponsId());
						} catch (Exception e) {
							logger.info("用户无法领取该优惠劵");
						}
					}
				}
				
				//修改历史记录
				memberCardHistory.setTransactionNumber(transactionNumber);
				memberCardHistory.setStatus(ShopClientStatus.MEMBER.toIntStatus());
				
				memberCardHistoryDAO.update(memberCardHistory);
				shopClientDAO.update(shopClient);

			} else if (attach.equals(Constants.WECHAT_ATTACH_FOR_MEMBER)) {
				/*
				 * MemberSign memberSign =
				 * memberSignDAO.findByMemberId(member.getId());
				 * if(memberSign!=null &&
				 * StringUtils.isNotBlank(memberSign.getId())){
				 * memberSign.setStatus(MemberSignStatus.PASS.toIntValue());
				 * memberSignDAO.update(memberSign);
				 * 
				 * if(StringUtils.isNotBlank(memberSign.getIdentity())){
				 * member.setIdentity(memberSign.getIdentity()); }
				 * member.setName(memberSign.getName());
				 * if(StringUtils.isBlank(member.getMobilePhone())){
				 * member.setMobilePhone(memberSign.getMobilePhone()); }
				 * 
				 * member.setStatus(MemberStatus.ACTIVE.toIntValue());
				 * memberDAO.update(member);
				 * 
				 * MemberConfig memberConfig =
				 * memberConfigDAO.getMemberConfig(member.getId());
				 * if(StringUtils.isNotBlank(memberConfig.getId())){
				 * memberConfig.setLevel(MemberLevelCode.STAIR.toIntValue());
				 * memberConfigDAO.update(memberConfig); } }
				 */
			} else if (attach.equals(Constants.WECHAT_ATTACH_FOR_VIP)) {
				UserVip userVip = userVipDAO.query(orderNumber);
				if (userVip == null) {
					throw new UserVipNotFoundException("User vip not found");
				}
				
				//检查是否有使用的VIP
				UserVip vip = userVipDAO.checkUserVip(user.getId());
				if(vip != null){
					vip.setIsUse(IsUse.NO.toIntValue());
					userVipDAO.update(vip);
				}
				
				userVip.setType(UserVipType.BUY.toIntType());
				userVip.setIsUse(Is.YES.toIntValue());
				userVipDAO.update(userVip);

				// 添加身份历史
				VipHistory vipHistory = new VipHistory();
				vipHistory.setUserId(user.getId());
				vipHistory.setVipId(userVip.getVipId());
				vipHistory.setTransactionNumber(transactionNumber);
				vipHistory.setPayMoney(payMoney);
				vipHistory.setPayTime(new Date());
				vipHistory.setPayWay(PayWay.WECHAT.toIntValue());
				vipHistoryDAO.insert(vipHistory);

				// 更新余额
				UserConfig userConfig = userConfigDAO.getUserConfig(user.getId());
				userConfig.setPileMoney(userConfig.getPileMoney() + payMoney);
				userConfig.setCurrentMoney(userConfig.getCurrentMoney() + payMoney);
				userConfigDAO.update(userConfig);

			} else if (attach.equals(Constants.WECHAT_ATTACH_FOR_SHOP_ORDER_NUMBER)) {
				if (user == null || StringUtils.isBlank(user.getId()))
					throw new UserNotFoundException("User not found");

				Orders orders = ordersDAO.findByShopOrderNumber(user.getId(), orderNumber);
				if (orders == null)
					throw new OrderNotFoundException("Orders not found");

				String userId = user.getId();
				orders.setTransactionNumber(transactionNumber);
				orders.setPayTime(DateUtil.parseDate(DateUtil.DATETIME_PATTERN_SECOND_SHORT, timeEnd));
				orders.setPayWay(PayWay.WECHAT.toIntValue());
				if (orders.getType() == OrderType.EAT.toIntValue()) {
					orders.setStatus(OrderStatus.COMPLETE.toIntValue());
				}else{
					orders.setStatus(OrderStatus.PAID.toIntValue());
				}
				
				ordersDAO.update(orders);
				
				// 升级会员卡
				Shop csShop = shopDAO.query(orders.getShopId());
				String csId = csShop.getIsChain() == IsChainStatus.YES.toIntStatus() ? csShop.getChainId()
						: csShop.getId();
				if(StringUtils.isNotBlank(csId)){
					memberCardService.receiveByShop(userId, csId, csShop.getIsChain());
				}else{
					throw new ChainShopException("csId is required.");
				}
				// 检查是否满足享有二级分润条件
				SystemConfig systemConfig = systemConfigDAO.find();
				if (systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()) {
					Double value = ordersDAO.sumPayMoney(userId);
					if (value >= systemConfig.getSellValue()) {
						User userParams = userDAO.query(userId);
						userParams.setIsMemberSell(Is.YES.toIntValue());
						userDAO.update(userParams);
					}

					// 财务报表及资产管理
					OrdersDataHistory ordersDataHistory = new OrdersDataHistory();
					ordersDataHistory.setOrdersId(orders.getId());
					ordersDataHistory.setShopId(orders.getShopId());
					ordersDataHistory.setOrderNumber(orders.getOrderNumber());
					ordersDataHistory.setShopOrderNumber(orders.getShopOrderNumber());
					ordersDataHistory.setRealMoney(orders.getRealMoney());
					ordersDataHistory.setTransactionNumber(orders.getTransactionNumber());
					ordersDataHistory.setPayMoney(orders.getPayMoney());
					ordersDataHistory.setPostage(orders.getPostage());
					ordersDataHistory.setStatus(OrdersDataHistoryStatus.CLOSE.toIntValue());

					UserCoupons userCoupons = userCouponsDAO.getUserCoupons(userId, orders.getId(), orderNumber);
					if (userCoupons != null) {
						ordersDataHistory.setCouponsId(orders.getUserCouponsId());
						ordersDataHistory.setCouponsType(userCoupons.getCouponsType());
						if (userCoupons.getCouponsType() == CouponsType.SHOP.toIntValue()) {
							ordersDataHistory.setCouponsMoney(orders.getCouponsMoney());
						} else {
							Double avg = orders.getPayMoney() / payMoney * orders.getCouponsMoney();
							ordersDataHistory.setCouponsMoney(Format.decimal(avg));
						}
					}
					OrdersDataHistory ordersDataHistoryparams = ordersDataHistoryDAO.insert(ordersDataHistory);

					int number = 0;
					List<OrdersGoods> ordersGoodsList = ordersGoodsDAO.getOrderGoodsByOrderId(orders.getId());
					for (OrdersGoods ordersGoods : ordersGoodsList) {
						couponsMoney += orders.getCouponsMoney();
						number += ordersGoods.getNumber();
						Goods goods = goodsDAO.query(ordersGoods.getGoodsId());
						if (goods.getIsOpenSku() == Is.YES.toIntValue()) {
							SkuContent skuContent = skuContentDAO.query(ordersGoods.getSkuContentId());
							skuContent.setStock(skuContent.getStock() - ordersGoods.getNumber());// 库存
							skuContentDAO.update(skuContent);

							// 添加待结算金额
							Shop shop = shopDAO.query(orders.getShopId());
							Double sumGoodsMoney = skuContent.getPrice() * number;
							Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() / 100);
							if (goods.getIsOpenRebate() == Is.YES.toIntValue()
									&& goods.getIsOpenSell() == Is.YES.toIntValue()) {
								shop.setAccumulativeMoney(shop.getAccumulativeMoney() + waitSumMoney);
								shop.setMonthIncomeMoney(shop.getMonthIncomeMoney() + waitSumMoney);
								shop.setWithdrawalMoney(shop.getWithdrawalMoney() + waitSumMoney);
							} else {
								shop.setWaitSumMoney(shop.getWaitSumMoney() + waitSumMoney);
							}
							shopDAO.update(shop);

							OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
							Industry industry = industryDAO.query(shop.getIndustryId());
							dataHistory.setShopMoney(dataHistory.getShopMoney() + waitSumMoney);
							dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
							dataHistory.setIndustryFullName(industry.getName());
							ordersDataHistoryDAO.update(dataHistory);

							GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
							goodsDataHistory.setGoodsId(goods.getId());
							goodsDataHistory.setShopId(goods.getShopId());
							goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
							goodsDataHistory.setTypeId(goods.getTypeId());
							goodsDataHistory.setGoodsName(goods.getName());
							goodsDataHistory.setSkuContentName(skuContent.getStandards());
							goodsDataHistory.setNumber(number);
							goodsDataHistory.setPrice(skuContent.getPrice());
							goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
							goodsDataHistory.setProfit(goods.getProfit());
							goodsDataHistory.setShopMoney(waitSumMoney);
							goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
							goodsDataHistory.setCouponsMoney(
									sumGoodsMoney / orders.getPayMoney() * dataHistory.getCouponsMoney());
							GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);

							// 有SKU商品进入排队返利队列
							if (goods.getIsOpenRebate() == Is.YES.toIntValue()) {
								for (int i = 0; i < ordersGoods.getNumber(); i++) {
									RebateVO rebateVO = new RebateVO();
									rebateVO.setGoodsId(goods.getId());
									rebateVO.setSkuContentId(skuContent.getId());
									rebateVO.setPrice(skuContent.getPrice());
									rebateVO.setShopId(goods.getShopId());
									rebateVO.setGoodsName(goods.getName());
									rebateVO.setUserId(userId);
									rebateVO.setOrderId(ordersGoods.getOrderId());
									rebateVO.setOrderGoodsId(ordersGoods.getId());
									RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
									if (StringUtils.isNoneBlank(rebateInfo.getId())) {
										rebateService.updateRedate(rebateInfo);
									}
								}
							}

							if (goods.getIsOpenSell() == Is.YES.toIntValue()
									&& goods.getIsOpenRebate() == Is.YES.toIntValue()) {
								// 分销
								commissionHistoryService.add(userId, ordersGoods.getId(), user.getParentId(),
										ordersDataHistoryparams.getId(), goodsDataHistoryParam.getId());
							}
							goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
							Double profit = (goodsDataHistory.getPrice() * goodsDataHistory.getNumber())
									- goodsDataHistory.getShopMoney(); // 利润
							// 共分出多少钱
							Double sumMoney = goodsDataHistory.getReferrerMoney()
									+ goodsDataHistory.getPrimaryBenefitMoney()
									+ goodsDataHistory.getSecondBenefitMoney()
									+ goodsDataHistory.getShopGetBenefitMoney();
							Double grossMargin = profit - sumMoney; // 毛利
							Double grossMarginRate = grossMargin / profit * 100;// 毛利率
							if (!grossMarginRate.isNaN()) {
								goodsDataHistory.setGrossMargin(grossMargin);
								goodsDataHistory.setGrossMarginRate(grossMarginRate);
							}
							goodsDataHistoryDAO.update(goodsDataHistory);

						} else {
							goods.setStock(goods.getStock() - ordersGoods.getNumber());// 库存

							// 添加待结算金额
							Shop shop = shopDAO.query(orders.getShopId());
							Double sumGoodsMoney = goods.getPrice() * number;
							Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() / 100);
							if (goods.getIsOpenRebate() == Is.YES.toIntValue()) {
								shop.setAccumulativeMoney(shop.getAccumulativeMoney() + waitSumMoney);
								shop.setMonthIncomeMoney(shop.getMonthIncomeMoney() + waitSumMoney);
								shop.setWithdrawalMoney(shop.getWithdrawalMoney() + waitSumMoney);
							} else {
								shop.setWaitSumMoney(shop.getWaitSumMoney() + waitSumMoney);
							}
							shopDAO.update(shop);

							OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
							Industry industry = industryDAO.query(shop.getIndustryId());
							dataHistory.setShopMoney(dataHistory.getShopMoney() + waitSumMoney);
							dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
							dataHistory.setIndustryFullName(industry.getName());
							ordersDataHistoryDAO.update(dataHistory);

							GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
							goodsDataHistory.setGoodsId(goods.getId());
							goodsDataHistory.setShopId(goods.getShopId());
							goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
							goodsDataHistory.setTypeId(goods.getTypeId());
							goodsDataHistory.setGoodsName(goods.getName());
							goodsDataHistory.setNumber(number);
							goodsDataHistory.setPrice(goods.getPrice());
							goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
							goodsDataHistory.setProfit(goods.getProfit());
							goodsDataHistory.setShopMoney(waitSumMoney);
							goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
							goodsDataHistory.setCouponsMoney(
									sumGoodsMoney / orders.getPayMoney() * dataHistory.getCouponsMoney());
							GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);

							// 没有SKU商品进入排队返利队列
							if (goods.getIsOpenRebate() == Is.YES.toIntValue()) {
								for (int i = 0; i < ordersGoods.getNumber(); i++) {
									RebateVO rebateVO = new RebateVO();
									rebateVO.setGoodsId(goods.getId());
									rebateVO.setPrice(goods.getPrice());
									rebateVO.setShopId(goods.getShopId());
									rebateVO.setGoodsName(goods.getName());
									rebateVO.setUserId(userId);
									rebateVO.setOrderId(ordersGoods.getOrderId());
									rebateVO.setOrderGoodsId(ordersGoods.getId());
									RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
									if (StringUtils.isNoneBlank(rebateInfo.getId())) {
										rebateService.updateRedate(rebateInfo);
									}
								}
							}
							if (goods.getIsOpenSell() == Is.YES.toIntValue()
									&& goods.getIsOpenRebate() == Is.YES.toIntValue()) {
								commissionHistoryService.add(userId, ordersGoods.getId(), user.getParentId(),
										ordersDataHistoryparams.getId(), goodsDataHistoryParam.getId());
							}

							goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
							Double profit = (goodsDataHistory.getPrice() * goodsDataHistory.getNumber())
									- goodsDataHistory.getShopMoney(); // 利润
							// 共分出多少钱
							Double sumMoney = goodsDataHistory.getReferrerMoney()
									+ goodsDataHistory.getPrimaryBenefitMoney()
									+ goodsDataHistory.getSecondBenefitMoney()
									+ goodsDataHistory.getShopGetBenefitMoney();
							Double grossMargin = profit - sumMoney; // 毛利
							Double grossMarginRate = grossMargin / profit * 100;// 毛利率
							if (!grossMarginRate.isNaN()) {
								goodsDataHistory.setGrossMargin(grossMargin);
								goodsDataHistory.setGrossMarginRate(grossMarginRate);
							}
							goodsDataHistoryDAO.update(goodsDataHistory);
						}
						goods.setSalesVolume(goods.getSalesVolume() + ordersGoods.getNumber());// 销量
						goodsDAO.update(goods);

						// 生成购买记录
						UserGoods userGoods = new UserGoods();
						userGoods.setShopId(orders.getShopId());
						userGoods.setGoodsId(ordersGoods.getGoodsId());
						userGoods.setUserId(user.getId());
						userGoods.setType(UserGoodsType.BUY.toIntValue());
						userGoods.setNumber(ordersGoods.getNumber());
						userGoodsDAO.insert(userGoods);

						OrdersDataHistory newOrdersDataHistory = ordersDataHistoryDAO
								.query(ordersDataHistoryparams.getId());
						if (newOrdersDataHistory != null) {
							Double profit = newOrdersDataHistory.getPayMoney() - newOrdersDataHistory.getPostage()
									- newOrdersDataHistory.getShopMoney();
							Double sumMoney = newOrdersDataHistory.getShareBenefitMoney()
									+ newOrdersDataHistory.getReferrerMoney() + newOrdersDataHistory.getAgencyBenefit()
									+ newOrdersDataHistory.getAgencyAccount();
							Double grossMargin = profit - sumMoney; // 毛利
							Double grossMarginRate = grossMargin / profit * 100;// 毛利率
							if (!grossMarginRate.isNaN()) {
								newOrdersDataHistory.setGrossMargin(grossMargin);
								newOrdersDataHistory.setGrossMarginRate(grossMarginRate);
							}
							ordersDataHistoryDAO.update(newOrdersDataHistory);
						}

					}

					// 添加交易记录
					PayHistory payHistory = new PayHistory();
					payHistory.setShopId(orders.getShopId());
					payHistory.setUserId(userId);
					payHistory.setMoney(payMoney);
					payHistory.setShopOrderNumber(orders.getShopOrderNumber());
					payHistory.setOrderNumber(orders.getOrderNumber());
					payHistory.setType(PayHistoryType.BUY.toIntValue());
					payHistory.setWay(PayWay.WECHAT.toIntValue());
					payHistoryDAO.insert(payHistory);

					// 插入交易记录
					TransactionAddVO transactionAddVO = new TransactionAddVO();
					BeanUtils.copyProperties(orders, transactionAddVO);
					transactionAddVO.setOrderId(orders.getId());
					transactionAddVO.setOrderType(orders.getType());
					transactionAddVO.setType(TransactionType.PAY.toIntValue());
					transactionAddVO.setNumber(number);
					transactionService.add(transactionAddVO);

				}
				
				//消费赠送乐积分
				if(systemConfig.getIsOpenConsume() == Is.YES.toIntValue()){
					UserConfig userConfig = userConfigDAO.getUserConfig(user.getId());
					Double sum = (payMoney * systemConfig.getConsumeValue() / 100);
					
					if(sum >= 0){
						userConfig.setPileIntegral(userConfig.getPileIntegral() + sum);
						userConfig.setCurrentIntegral(userConfig.getCurrentIntegral() + sum);
						userConfigDAO.update(userConfig);
						
						//消费赠送积分
						DetailIntegral detailLeIntegral = new DetailIntegral();
						detailLeIntegral.setUserId(user.getId());
						detailLeIntegral.setValue(sum);
						detailLeIntegral.setTransactionNumber(transactionNumber);
						detailLeIntegral.setOrdersNumber(orderNumber);
						detailLeIntegral.setType(DetailType.ADD.toIntValue());
						detailLeIntegral.setStatus(DetailStatus.SUCCESS.toIntValue());
						detailLeIntegral.setNewIntegral(sum);
						detailLeIntegral.setPurpose("消费赠送积分");
						detailIntegralDAO.insert(detailLeIntegral);
					}
				}
				
				// 打印小票(为堂食的才打印小票)
				if (orders.getType() == OrderType.EAT.toIntValue() ||orders.getType() == OrderType.EXTRACT.toIntValue() || orders.getType() == OrderType.DELIVERY.toIntValue()) {
					printingService.printIndex(orders.getShopId(), orders.getId());
				}

			} else {
				if (user == null || StringUtils.isBlank(user.getId()))
					throw new UserNotFoundException("User not found");

				List<Orders> list = ordersDAO.getOrderByPay(user.getId(), orderNumber);
				for (Orders orders : list) {
					if (list.size() < 0)
						throw new OrderNotFoundException("Orders not found");

					couponsMoney += orders.getCouponsMoney();
					String userId = user.getId();
					orders.setTransactionNumber(transactionNumber);
					orders.setPayTime(DateUtil.parseDate(DateUtil.DATETIME_PATTERN_SECOND_SHORT, timeEnd));
					orders.setPayWay(PayWay.WECHAT.toIntValue());
					if (orders.getType() == OrderType.EAT.toIntValue()) {
						orders.setStatus(OrderStatus.COMPLETE.toIntValue());
					}else{
						orders.setStatus(OrderStatus.PAID.toIntValue());
					}
					
					ordersDAO.update(orders);
					
					// 升级会员卡
					Shop csShop = shopDAO.query(orders.getShopId());
					String csId = csShop.getIsChain() == IsChainStatus.YES.toIntStatus() ? csShop.getChainId()
							: csShop.getId();
					if(StringUtils.isNotBlank(csId)){
						memberCardService.receiveByShop(userId, csId, csShop.getIsChain());
					}else{
						throw new ChainShopException("csId is required.");
					}
					// 检查是否满足享有二级分润条件
					SystemConfig systemConfig = systemConfigDAO.find();
					if (systemConfig.getIsOpenMemberSell() == Is.YES.toIntValue()) {
						Double value = ordersDAO.sumPayMoney(userId);
						if (value >= systemConfig.getSellValue()) {
							User userParams = userDAO.query(userId);
							userParams.setIsMemberSell(Is.YES.toIntValue());
							userDAO.update(userParams);
						}
					}

					OrdersDataHistory ordersDataHistory = new OrdersDataHistory();
					ordersDataHistory.setOrdersId(orders.getId());
					ordersDataHistory.setShopId(orders.getShopId());
					ordersDataHistory.setOrderNumber(orders.getOrderNumber());
					ordersDataHistory.setShopOrderNumber(orders.getShopOrderNumber());
					ordersDataHistory.setRealMoney(orders.getRealMoney());
					ordersDataHistory.setTransactionNumber(orders.getTransactionNumber());
					ordersDataHistory.setPayMoney(orders.getPayMoney());
					ordersDataHistory.setPostage(orders.getPostage());
					ordersDataHistory.setStatus(OrdersDataHistoryStatus.CLOSE.toIntValue());
					UserCoupons userCoupons = userCouponsDAO.getUserCoupons(userId, orders.getId(), orderNumber);
					if (userCoupons != null) {
						ordersDataHistory.setCouponsId(orders.getUserCouponsId());
						ordersDataHistory.setCouponsType(userCoupons.getCouponsType());
						if (userCoupons.getCouponsType() == CouponsType.SHOP.toIntValue()) {
							ordersDataHistory.setCouponsMoney(orders.getCouponsMoney());
						} else {
							Double avg = orders.getPayMoney() / payMoney * orders.getCouponsMoney();
							ordersDataHistory.setCouponsMoney(Format.decimal(avg));
						}
					}
					OrdersDataHistory ordersDataHistoryparams = ordersDataHistoryDAO.insert(ordersDataHistory);

					int number = 0;
					List<OrdersGoods> ordersGoodsList = ordersGoodsDAO.getOrderGoodsByOrderId(orders.getId());
					for (OrdersGoods ordersGoods : ordersGoodsList) {

						number += ordersGoods.getNumber();
						Goods goods = goodsDAO.query(ordersGoods.getGoodsId());
						if (goods.getIsOpenSku() == Is.YES.toIntValue()) {
							SkuContent skuContent = skuContentDAO.query(ordersGoods.getSkuContentId());
							skuContent.setStock(skuContent.getStock() - ordersGoods.getNumber());// 库存
							skuContentDAO.update(skuContent);

							// 添加待结算金额
							Shop shop = shopDAO.query(goods.getShopId());
							Double sumGoodsMoney = skuContent.getPrice() * ordersGoods.getNumber();
							Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() / 100);
							if (goods.getIsOpenRebate() == Is.YES.toIntValue()
									&& goods.getIsOpenSell() == Is.YES.toIntValue()) {
								shop.setAccumulativeMoney(shop.getAccumulativeMoney() + waitSumMoney);
								shop.setMonthIncomeMoney(shop.getMonthIncomeMoney() + waitSumMoney);
								shop.setWithdrawalMoney(shop.getWithdrawalMoney() + waitSumMoney);
							} else {
								shop.setWaitSumMoney(shop.getWaitSumMoney() + waitSumMoney);
							}
							shopDAO.update(shop);

							OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
							Industry industry = industryDAO.query(shop.getIndustryId());
							dataHistory.setShopMoney(dataHistory.getShopMoney() + waitSumMoney);
							dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
							dataHistory.setIndustryFullName(industry.getName());
							ordersDataHistoryDAO.update(dataHistory);

							GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
							goodsDataHistory.setGoodsId(goods.getId());
							goodsDataHistory.setShopId(goods.getShopId());
							goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
							goodsDataHistory.setTypeId(goods.getTypeId());
							goodsDataHistory.setGoodsName(goods.getName());
							goodsDataHistory.setSkuContentName(skuContent.getStandards());
							goodsDataHistory.setNumber(ordersGoods.getNumber());
							goodsDataHistory.setPrice(skuContent.getPrice());
							goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
							goodsDataHistory.setProfit(goods.getProfit());
							goodsDataHistory.setShopMoney(waitSumMoney);
							goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
							goodsDataHistory.setCouponsMoney(
									sumGoodsMoney / orders.getPayMoney() * dataHistory.getCouponsMoney());
							GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);

							// 有SKU商品进入排队返利队列
							if (goods.getIsOpenRebate() == Is.YES.toIntValue()) {
								for (int i = 0; i < ordersGoods.getNumber(); i++) {

									RebateVO rebateVO = new RebateVO();
									rebateVO.setGoodsId(goods.getId());
									rebateVO.setSkuContentId(skuContent.getId());
									rebateVO.setPrice(skuContent.getPrice());
									rebateVO.setShopId(goods.getShopId());
									rebateVO.setUserId(userId);
									rebateVO.setOrderId(ordersGoods.getOrderId());
									rebateVO.setGoodsName(goods.getName());
									rebateVO.setOrderGoodsId(ordersGoods.getId());
									RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
									if (StringUtils.isNoneBlank(rebateInfo.getId())) {
										rebateService.updateRedate(rebateInfo);
									}
								}
							}

							if (goods.getIsOpenSell() == Is.YES.toIntValue()
									&& goods.getIsOpenSell() == Is.YES.toIntValue()) {
								// 分销
								commissionHistoryService.add(userId, ordersGoods.getId(), user.getParentId(),
										ordersDataHistoryparams.getId(), goodsDataHistoryParam.getId());
							}

							goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
							Double profit = (goodsDataHistory.getPrice() * goodsDataHistory.getNumber())
									- goodsDataHistory.getShopMoney(); // 利润
							// 共分出多少钱
							Double sumMoney = goodsDataHistory.getReferrerMoney()
									+ goodsDataHistory.getPrimaryBenefitMoney()
									+ goodsDataHistory.getSecondBenefitMoney()
									+ goodsDataHistory.getShopGetBenefitMoney();
							Double grossMargin = profit - sumMoney; // 毛利
							Double grossMarginRate = grossMargin / profit * 100;// 毛利率
							if (!grossMarginRate.isNaN()) {
								goodsDataHistory.setGrossMargin(grossMargin);
								goodsDataHistory.setGrossMarginRate(grossMarginRate);
							}
							goodsDataHistoryDAO.update(goodsDataHistory);
						} else {
							goods.setStock(goods.getStock() - ordersGoods.getNumber());// 库存

							// 添加待结算金额
							Shop shop = shopDAO.query(goods.getShopId());
							Double sumGoodsMoney = goods.getPrice() * ordersGoods.getNumber();
							Double waitSumMoney = sumGoodsMoney - (sumGoodsMoney * goods.getProfit() / 100);
							if (goods.getIsOpenRebate() == Is.YES.toIntValue()
									&& goods.getIsOpenSell() == Is.YES.toIntValue()) {
								shop.setAccumulativeMoney(shop.getAccumulativeMoney() + waitSumMoney);
								shop.setMonthIncomeMoney(shop.getMonthIncomeMoney() + waitSumMoney);
								shop.setWithdrawalMoney(shop.getWithdrawalMoney() + waitSumMoney);
							} else {
								shop.setWaitSumMoney(shop.getWaitSumMoney() + waitSumMoney);
							}
							shopDAO.update(shop);

							OrdersDataHistory dataHistory = ordersDataHistoryDAO.query(ordersDataHistoryparams.getId());
							Industry industry = industryDAO.query(shop.getIndustryId());
							dataHistory.setShopMoney(dataHistory.getShopMoney() + waitSumMoney);
							dataHistory.setProfitMoney(dataHistory.getProfitMoney() + (sumGoodsMoney - waitSumMoney));
							dataHistory.setIndustryFullName(industry.getName());
							ordersDataHistoryDAO.update(dataHistory);

							GoodsDataHistory goodsDataHistory = new GoodsDataHistory();
							goodsDataHistory.setGoodsId(goods.getId());
							goodsDataHistory.setShopId(goods.getShopId());
							goodsDataHistory.setOrdersDataHistoryId(ordersDataHistoryparams.getId());
							goodsDataHistory.setTypeId(goods.getTypeId());
							goodsDataHistory.setGoodsName(goods.getName());
							goodsDataHistory.setNumber(ordersGoods.getNumber());
							goodsDataHistory.setPrice(goods.getPrice());
							goodsDataHistory.setIsOpenRebate(goods.getIsOpenRebate());
							goodsDataHistory.setProfit(goods.getProfit());
							goodsDataHistory.setShopMoney(waitSumMoney);
							goodsDataHistory.setProfitMoney(sumGoodsMoney - waitSumMoney);
							goodsDataHistory.setCouponsMoney(
									sumGoodsMoney / orders.getPayMoney() * dataHistory.getCouponsMoney());
							GoodsDataHistory goodsDataHistoryParam = goodsDataHistoryDAO.insert(goodsDataHistory);

							// 没有SKU商品进入排队返利队列
							if (goods.getIsOpenRebate() == Is.YES.toIntValue()) {
								for (int i = 0; i < ordersGoods.getNumber(); i++) {
									RebateVO rebateVO = new RebateVO();
									rebateVO.setGoodsId(goods.getId());
									rebateVO.setPrice(goods.getPrice());
									rebateVO.setShopId(goods.getShopId());
									rebateVO.setUserId(userId);
									rebateVO.setGoodsName(goods.getName());
									rebateVO.setOrderId(ordersGoods.getOrderId());
									rebateVO.setOrderGoodsId(ordersGoods.getId());
									RebateInfo rebateInfo = rebateService.addRebate(rebateVO);
									if (StringUtils.isNoneBlank(rebateInfo.getId())) {
										rebateService.updateRedate(rebateInfo);
									}
								}
							}
							if (goods.getIsOpenSell() == Is.YES.toIntValue()
									&& goods.getIsOpenSell() == Is.YES.toIntValue()) {
								// 分销
								commissionHistoryService.add(userId, ordersGoods.getId(), user.getParentId(),
										ordersDataHistoryparams.getId(), goodsDataHistoryParam.getId());
							}

							goodsDataHistory = goodsDataHistoryDAO.query(goodsDataHistoryParam.getId());
							Double profit = (goodsDataHistory.getPrice() * goodsDataHistory.getNumber())
									- goodsDataHistory.getShopMoney(); // 利润
							// 共分出多少钱
							Double sumMoney = goodsDataHistory.getReferrerMoney()
									+ goodsDataHistory.getPrimaryBenefitMoney()
									+ goodsDataHistory.getSecondBenefitMoney()
									+ goodsDataHistory.getShopGetBenefitMoney();
							Double grossMargin = profit - sumMoney; // 毛利
							Double grossMarginRate = grossMargin / profit * 100;// 毛利率
							if (!grossMarginRate.isNaN()) {
								goodsDataHistory.setGrossMargin(grossMargin);
								goodsDataHistory.setGrossMarginRate(grossMarginRate);
							}
							goodsDataHistoryDAO.update(goodsDataHistory);
						}

						goods.setSalesVolume(goods.getSalesVolume() + ordersGoods.getNumber());// 销量
						goodsDAO.update(goods);

						// 生成购买记录
						UserGoods userGoods = new UserGoods();
						userGoods.setShopId(orders.getShopId());
						userGoods.setGoodsId(ordersGoods.getGoodsId());
						userGoods.setUserId(user.getId());
						userGoods.setType(UserGoodsType.BUY.toIntValue());
						userGoods.setNumber(ordersGoods.getNumber());
						userGoodsDAO.insert(userGoods);

						// 统计订单数据表毛利
						OrdersDataHistory newOrdersDataHistory = ordersDataHistoryDAO
								.query(ordersDataHistoryparams.getId());
						if (newOrdersDataHistory != null) {
							Double profit = newOrdersDataHistory.getPayMoney() - newOrdersDataHistory.getPostage()
									- newOrdersDataHistory.getShopMoney();
							Double sumMoney = newOrdersDataHistory.getShareBenefitMoney()
									+ newOrdersDataHistory.getReferrerMoney() + newOrdersDataHistory.getAgencyBenefit()
									+ newOrdersDataHistory.getAgencyAccount();
							Double grossMargin = profit - sumMoney; // 毛利
							Double grossMarginRate = grossMargin / profit * 100;// 毛利率
							if (!grossMarginRate.isNaN()) {
								newOrdersDataHistory.setGrossMargin(grossMargin);
								newOrdersDataHistory.setGrossMarginRate(grossMarginRate);
							}
							ordersDataHistoryDAO.update(newOrdersDataHistory);
						}
					}
					
					//消费赠送乐积分
					if(systemConfig.getIsOpenConsume() == Is.YES.toIntValue()){
						UserConfig userConfig = userConfigDAO.getUserConfig(user.getId());
						Double sum = (payMoney * systemConfig.getConsumeValue() / 100);
						
						if(sum >= 0){
							userConfig.setPileIntegral(userConfig.getPileIntegral() + sum);
							userConfig.setCurrentIntegral(userConfig.getCurrentIntegral() + sum);
							userConfigDAO.update(userConfig);
							
							//消费赠送积分
							DetailIntegral detailLeIntegral = new DetailIntegral();
							detailLeIntegral.setUserId(user.getId());
							detailLeIntegral.setValue(sum);
							detailLeIntegral.setTransactionNumber(transactionNumber);
							detailLeIntegral.setOrdersNumber(orderNumber);
							detailLeIntegral.setType(DetailType.ADD.toIntValue());
							detailLeIntegral.setStatus(DetailStatus.SUCCESS.toIntValue());
							detailLeIntegral.setNewIntegral(sum);
							detailLeIntegral.setPurpose("消费赠送积分");
							detailIntegralDAO.insert(detailLeIntegral);
						}
					}
					

					// 添加交易记录
					PayHistory payHistory = new PayHistory();
					payHistory.setShopId(orders.getShopId());
					payHistory.setUserId(userId);
					payHistory.setMoney(payMoney);
					payHistory.setShopOrderNumber(orders.getShopOrderNumber());
					payHistory.setOrderNumber(orders.getOrderNumber());
					payHistory.setType(PayHistoryType.BUY.toIntValue());
					payHistory.setWay(PayWay.WECHAT.toIntValue());
					payHistoryDAO.insert(payHistory);

					// 插入交易记录
					TransactionAddVO transactionAddVO = new TransactionAddVO();
					BeanUtils.copyProperties(orders, transactionAddVO);
					transactionAddVO.setOrderId(orders.getId());
					transactionAddVO.setOrderType(orders.getType());
					transactionAddVO.setType(TransactionType.PAY.toIntValue());
					transactionAddVO.setNumber(number);
					transactionService.add(transactionAddVO);
					
					// 打印小票(为堂食的才打印小票)
					if (orders.getType() == OrderType.EAT.toIntValue() || orders.getType() == OrderType.EXTRACT.toIntValue() || orders.getType() == OrderType.DELIVERY.toIntValue()) {
						printingService.printIndex(orders.getShopId(), orders.getId());
					}
				}
			}
			SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
			parameters.put("return_code", "SUCCESS");
			parameters.put("return_msg", "OK");
			String resultXML = WeChatUtils.getRequestXml(parameters);

			/*List<Orders> orderList = ordersDAO.getOrderByOrderNumber(orderNumber);
			if (orderList.size() > 0) {
				String shopId = null;
				for (Orders orders : orderList) {
					shopId = orders.getShopId();
				}
				Shop shop = shopDAO.query(shopId);
				WechatConfigBO params;
				if (shop.getIsChain() == Is.NO.toIntValue()) {
					params = wechatConfigDAO.getWechatConfigByShopId(shopId);
				} else {
					Chain chain = chainDAO.query(shop.getChainId());
					params = wechatConfigDAO.getWechatConfigByShopId(chain.getId());
				}

				// 发送消息模板
				String key = DIYKey.getFormIdByOrderNumber(orderNumber);
				UserFormIdVO formIdVO = userCacheDAO.getHash(key, UserFormIdVO.class);
				if (formIdVO != null) {
					String wechatCodeKey = DIYKey.getWechatCodeKey(params.getWcId());
					WechatConfig wechatConfig = wechatConfigCacheDAO.getHash(wechatCodeKey, WechatConfig.class);
					if (wechatConfig == null) {
						wechatConfig = wechatConfigDAO.getWechatConfigByWcId(params.getWcId());
						wechatConfigCacheDAO.addHash(key, wechatConfig);
					}

					Map<String, Object> data = TemplateMessageUtil.getMessageData(
							new String[] { transactionNumber, orderNumber, payMoney.toString(), couponsMoney.toString(),
									DateUtil.format(new Date()), "400-931-8788", "如有疑问,请联系客服" });
					TemplateMessageParam tmp = new TemplateMessageParam();
					tmp.setTouser(openId);
					tmp.setTemplateId(TemplateMessageUtil.BUY_SUCCESS);// 模板ID
					tmp.setFormId(formIdVO.getFormId());
					tmp.setEmphasisKeyword("keyword3.DATA");
					tmp.setData(data);// 内容
					TemplateMessageUtil.pullMessage(tmp, wechatConfig);
				}
			}*/
			return resultXML;
		} catch (Exception e) {
			logger.error("pay retrun error:", e);
			SortedMap<Object, Object> parameters = new TreeMap<Object, Object>();
			parameters.put("return_code", "FAIL");
			parameters.put("return_msg", "NO");
			String resultXML = WeChatUtils.getRequestXml(parameters);
			return resultXML;
		}

	}

	@Override
	public ResultVO wechatPay(HttpServletRequest request, String userId, String ordersId, String tradeType,
			String wcId) {
		ResultVO result = new ResultVO();
		UserBO userBO = userDAO.findUserId(userId);
		if (userBO == null || StringUtils.isBlank(userBO.getId()))
			throw new UserNotFoundException("User not found");

		Orders orders = ordersDAO.query(ordersId);
		if (orders == null || StringUtils.isBlank(orders.getId())) {
			result.setStatus(APICodeStatus.ORDER_NOT_FOUND);
			result.setMessage("Orders not found.");
			return result;
		}

		// 发起微信支付申请
		// String body = messageService.getMessage(WECHAT_BODY_KEY, new
		// String[]{orderNumber}, Lang.ZH_CN.toStringValue());
		String wechatKey = DIYKey.getWechatCodeKey(wcId);
		WechatConfig wechatConfig = wechatConfigCacheDAO.getHash(wechatKey, WechatConfig.class);
		if (wechatConfig == null) {
			wechatConfig = wechatConfigDAO.getWechatConfigByWcId(wcId);
			boolean is = wechatConfigCacheDAO.addHash(wechatKey, wechatConfig);
			if (!is) {
				throw new WechatConfigAddException("找不到微信配置");
			}
		}

		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setAttach(Constants.WECHAT_ATTACH_FOR_SHOP_ORDER_NUMBER);
		orderInfo.setOutTradeNo(orders.getShopOrderNumber());
		orderInfo.setBody(WECHAT_BODY_KEY + "-" + orders.getShopOrderNumber());
		orderInfo.setTotalFee(Math.round(orders.getPayMoney() * 100));
		orderInfo.setSpbillCreateIp(RequestUtil.getRealIp(request));
		orderInfo.setOpenId(userBO.getOpenId());
		orderInfo.setTradeType(tradeType);
		PayParam payParam = WeChatUtils.getPayParam(orderInfo, wechatConfig);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("shopOrderNumber", orders.getShopOrderNumber());
		map.put("orderNumber", orders.getOrderNumber());
		map.put("orderId", orders.getId());
		map.put("patParam", payParam);
		result.setData(map);
		return result;
	}

	@Override
	public ResultVO wechatPaySuccess(String shopOrderNumber) {
		ResultVO result = new ResultVO();
		Orders orders = ordersDAO.getOrderByShopOrderNumber(shopOrderNumber);
		result.setData(orders);
		return result;
	}

	@Override
	public ResultVO logisticsTrace(String ordersId) {
		ResultVO result = new ResultVO();
		OrdersBO ordersBO = ordersDAO.findLogistics(ordersId);
		if (ordersBO == null || StringUtils.isBlank(ordersBO.getLogisticsNumber())) {
			throw new OrdersNotFoundException("找不到订单");
		}
		Map<String, Object> map = new HashMap<String, Object>();
		LogisticsResultDate logisticsResultDate = LogisticsUtil.expressQuery(ordersBO.getLogisticsNumber(),
				ordersBO.getLogisticsCode());
		if (logisticsResultDate == null) {
			throw new LogisticsNumberErrorException("未查询到该物流信息");
		}
		map.put("logisticsResultDate", logisticsResultDate.getResult());
		map.put("logisticsNumber", ordersBO.getLogisticsNumber());
		map.put("logisticsName", ordersBO.getLogisticsName());
		result.setData(map);
		return result;
	}

	@Override
	public ResultVO editStatusByShopOrderNumber(String shopOrderNumber, Integer status) {
		ResultVO result = new ResultVO();
		try {
			// 修改状态
			Orders orders = ordersDAO.getOrderByShopOrderNumber(shopOrderNumber);
			orders.setStatus(status);
			orders.setConfirmTime(DateUtil.getCurrentDate());
			orders.setConfirmType(ConfirmType.USER.toIntValue());
			ordersDAO.update(orders);

			// 更新店铺资产
			OrdersBO params = ordersDAO.findOrderById(orders.getId());
			if (orders != null && StringUtils.isNoneBlank(orders.getShopId())) {
				Double money = params.getPayMoney() - (params.getPayMoney() * params.getProfit() / 100);
				Shop shop = shopDAO.query(orders.getShopId());
				shop.setWithdrawalMoney(shop.getWithdrawalMoney() + money);
				shop.setAccumulativeMoney(shop.getAccumulativeMoney() + money);
				shop.setMonthIncomeMoney(shop.getMonthIncomeMoney() + money);
				if ((shop.getWaitSumMoney() - money) >= 0) {
					shop.setWaitSumMoney(shop.getWaitSumMoney() - money);
				}
				shopDAO.update(shop);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(APICodeStatus.ORDER_UPDATE_STATUS_IS_FAIL);
			result.setMessage("update orders status fail" + shopOrderNumber);
		}
		return result;
	}

	@Override
	@Transactional
	public ResultVO delOrders(String orderNumber) {
		ResultVO result = new ResultVO();

		String ordersGoodsId = ordersGoodsDAO.getOrderGoodsByOrderNumber(orderNumber);
		if (StringUtils.isNotBlank(ordersGoodsId)) {
			// ordersGoodsDAO.delete(ordersGoodsId);
			ordersGoodsDAO.updateToDelete(ordersGoodsId);
		}

		Orders orders = ordersDAO.getOrdersByOrderNumber(orderNumber);
		if (orders != null) {
			// ordersDAO.delete(orders);
			ordersDAO.updateToDelete(orders.getId());
		}
		return result;
	}

	@Override
	public ResultVO resetPayHistory() {
		ResultVO result = new ResultVO();
		List<Orders> list = ordersDAO.getOrderByStatus();
		for (Orders orders : list) {
			// 添加交易记录
			PayHistory payHistory = new PayHistory();
			payHistory.setShopId(orders.getShopId());
			payHistory.setUserId(orders.getUserId());
			payHistory.setMoney(orders.getPayMoney());
			payHistory.setShopOrderNumber(orders.getShopOrderNumber());
			payHistory.setOrderNumber(orders.getOrderNumber());
			payHistory.setType(PayHistoryType.BUY.toIntValue());
			payHistory.setWay(PayWay.WECHAT.toIntValue());
			payHistory.setCreatedTime(orders.getCreatedTime());
			payHistoryDAO.insert(payHistory);
		}
		return result;
	}

	@Override
	public ResultVO findAppletsOrderInfo(String userId, List<String> carts) {
		ResultVO result = new ResultVO();
		// 1.按照购物车ID数组查询所有的商品以及对应的店铺(分类好)
		Set<ShopDetailBO> shopSet = new HashSet<ShopDetailBO>();
		String cart = "";
		for (String s : carts) {
			cart += "'" + s + "',";
		}
		String shopId = "";

		cart = cart.substring(0, cart.length() - 1);
		List<CartBO> cartList = cartDAO.getCartExtendInfoById(cart);
		Double total = new Double(0);
		Double totalPostage = new Double(0);
		//总餐盒费
		Double sumFoodBoxCharge = new Double(0);
		if (cartList != null && cartList.size() > 0) {
			for (CartBO bo : cartList) {
				ShopDetailBO shopBo = new ShopDetailBO();
				shopBo.setShopId(bo.getShopId());
				shopBo.setShopName(bo.getShopName());
				shopBo.setShopLogo(bo.getShopHeadImgUrl());
				shopSet.add(shopBo);
			}
			Double foodBoxCharge = null;
			for (ShopDetailBO sbo : shopSet) {
				foodBoxCharge = new Double(0);
				if ("" == shopId) {
					shopId = sbo.getShopId();
				}

				Double realMoney = new Double(0);
				Double postage = new Double(0);
				List<GoodsDetailBO> list = new ArrayList<GoodsDetailBO>();
				for (CartBO bo : cartList) {
					if (bo.getShopId().equals(sbo.getShopId())) {
						GoodsDetailBO goodsBo = new GoodsDetailBO();
						//单商品累积餐盒费(单间餐盒费乘以数量)
						Double smallPlan = new Double(0);
						if(bo.getFoodBoxCharge() != null && bo.getNumber()!=null){
							smallPlan = (bo.getFoodBoxCharge()* bo.getNumber());
						}
						//店铺餐盒费累积
						foodBoxCharge+=smallPlan;
						BeanUtils.copyProperties(bo, goodsBo);
						goodsBo.setId(bo.getGoodsId());
						goodsBo.setName(bo.getGoodsName());
						//单商品餐盒费小计
						goodsBo.setFoodBoxCharge(smallPlan);
						if (goodsBo.getPrice() != null) {
							realMoney = realMoney+Format.decimal(goodsBo.getPrice() * goodsBo.getNumber());
						}
						if (!goodsBo.getPostagePrice().equals(new Double(0))) {
							postage += goodsBo.getPostagePrice();
						}
						list.add(goodsBo);
					}
				}
				total = realMoney + total;
				totalPostage += postage;
				//总店铺餐盒费累积
				sumFoodBoxCharge += foodBoxCharge;
				sbo.setPostage(postage);
				sbo.setRealMoney(realMoney);
				sbo.setGoods(list);
				//单店铺餐盒费累积
				sbo.setFoodBoxCharge(Format.decimal(foodBoxCharge));
			}
		}
		// 2.优惠劵信息查询，当前用户在当前商家中可用的优惠劵
		Shop shop = shopDAO.query(shopId);
		List<UserCouponsInfoBO> couponsList = userCouponsDAO.getCouponsByShopId(userId, shop.getChainId(),shop.getId());
		coupons: for (int i = 0; i < couponsList.size(); i++) {
			UserCouponsInfoBO ucBO = couponsList.get(i);
			if (ucBO.getThreshold().equals(CouponFullSubtraction.UNRESTRICTED.toIntValue())) {
				continue;
			}
			if (ucBO.getPlatform().equals(CouponsPlatform.INTERNAL.toIntValue())) {
				if (ucBO.getFullPriceReduction() > total) {
					couponsList.remove(ucBO);
					continue;
				}
			} else {
				for (ShopDetailBO sbo : shopSet) {
					if (ucBO.getShopId().equals(sbo.getShopId())) {
						if (ucBO.getThreshold().equals(CouponFullSubtraction.FULL_SUBTRACTION.toIntValue())) {
							if (ucBO.getFullPriceReduction() > sbo.getRealMoney()) {
								couponsList.remove(ucBO);
								continue coupons;
							}
						}
					}
				}
			}
		}
		List<CouponsDetailsVO> list = couponsService.formatCoupons(couponsList);
		// 3.将地址信息查询出来(默认)
		Address address = addressDAO.getDefalutAddress(userId);
		// 4.运费按照商品中的运费累计
		Map<String, Object> map = new HashMap<String, Object>();
		//
		/**
		 * 以下计算会员卡
		 */

		if (shop != null) {
			// 用户在该csId下的会员卡
			String csId = shop.getChainId() == null ? shop.getId() : shop.getChainId();
			MemberCard memberCard = memberCardDAO.findAllByCsId(csId, userId);
			if (memberCard != null) {
				List<MemberCardUseVO> memberCardUseVOList = new ArrayList<MemberCardUseVO>();
				// 是否包邮
				if (memberCard.getIsFreeCarriage() == Is.YES.toIntValue()) {

					MemberCardUseVO vo = new MemberCardUseVO();
					vo.setPrivilegeType(MemberCardUseType.FREE_SHIPPING.toIntValue());
					vo.setPrivilegeMoney(totalPostage);
					memberCardUseVOList.add(vo);
				}
				// 是否会员价
				if (memberCard.getIsDiscount() == Is.YES.toIntValue()) {
					Double discount = Format.decimal(total - total * (memberCard.getDiscount() / 10));

					MemberCardUseVO vo = new MemberCardUseVO();
					vo.setPrivilegeType(MemberCardUseType.DISCOUNT.toIntValue());
					vo.setPrivilegeMoney(discount);
					memberCardUseVOList.add(vo);
				}
				map.put("memberCardUseList", memberCardUseVOList);
			}
			ShopClient shopClient = shopClientDAO.findClientByUserId(userId, csId);
			map.put("shopClient", shopClient);
		}

		map.put("shop", shopSet);
		map.put("coupons", list);
		map.put("address", address);
		map.put("sumFoodBoxCharge", Format.decimal(sumFoodBoxCharge));
		result.setData(map);
		return result;
	}
}